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 Classes and Core Mechanics

bookEnhanced 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.java

Main.java

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:

Main.java

Main.java

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:

Main.java

Main.java

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 statement?

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

question mark

What is the case syntax of enhanced Switch statement?

正しい答えを選んでください

question mark

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

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  7

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  7
some-alt