Contenido del Curso
Java Extended
Java Extended
Enhanced Switch Statement
How to Optimize a Switch Statement?
Just like the if
-statement has the ternary operator, the switch
-statement has an enhanced version called the enhanced switch.
Let's take a look at the syntax right away:
Main
switch (variable) { case value1 -> { // code block } case value2 -> { // code block } // additional cases default -> { // code block } }
The enhanced switch statement uses a simplified syntax with ->
instead of case
and break
. It allows you to write concise code blocks for each case directly without the need for explicit break
statements.
Let's take a look at an example of using a switch statement. First, let's see a regular switch statement:
Main
package com.example; public class Main { public static void main(String[] args) { int a = 10; switch (a) { case 5: System.out.println("five"); break; case 0: System.out.println("zero"); break; case 10: System.out.println("ten"); break; default: System.out.println("no value"); break; } } }
Now let's replace it with the enhanced version to see the difference:
Main
package com.example; public class Main { public static void main(String[] args) { int a = 10; switch (a) { case 5 -> { System.out.println("five"); } case 0 -> { System.out.println("zero"); } case 10 -> { System.out.println("ten"); } default -> { System.out.println("no value"); } } } }
As you can see, the syntax has changed, and the code has become shorter. Additionally, we no longer need to explicitly write the break
keyword; the compiler now understands that it should stop executing the switch
statement after matching one of the cases.
In this way, we can simplify our switch
statement and write professional code.
¡Gracias por tus comentarios!