Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Enhanced Switch Statement | Deep Java Structure
Java Extended
course content

Conteúdo do Curso

Java Extended

Java Extended

1. Deep Java Structure
2. Methods
3. String Advanced
4. Classes
5. Classes Advanced

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:

java

Main

copy
123456789101112
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:

java

Main

copy
123456789101112131415161718192021
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:

java

Main

copy
123456789101112131415161718192021
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.

1. What is the case syntax of enhanced Switch-case statement?
2. Do we need to use ``break;`` keyword with enhanced switch?

What is the case syntax of enhanced Switch-case statement?

Selecione a resposta correta

Do we need to use break; keyword with enhanced switch?

Selecione a resposta correta

Tudo estava claro?

Seção 1. Capítulo 7
We're sorry to hear that something went wrong. What happened?
some-alt