Javatpoint Logo
Javatpoint Logo

Switch Case in Java 12

The switch case in Java has undergone some modification to add some new features in more recent versions of Java. In this tutorial, we are going to discuss the switch case in Java 12. However, before that, let's see an example that shows the implementation of the traditional switch case.

FileName: TraditionalSwitch.java

Output:

The day is not valid.
Days of Weekday.
Days of Weekend.

Using Switch Case of Java 12

In Java 12, the switch case has the following modifications:

  • There can be multiple labels with a single case.
  • The fallthrough will not occur even without the use of the break statement, which is not possible in the traditional switch expressions. We can return values via break value.
  • We can also return a value using an arrow.

Using Multiple Labels

FileName: LatestSwitchExpression.java

Output:

Eleven or Twelve
Thirteen or Fourteen
The number is invalid.
Fifteen or Seventeen or Nineteen
The number is invalid.

Returning Values Via Arrow

We can also use arrow (->) in our switch expressions. In this case, there is no need of the break statement to prevent the fall-through. The fall-through will not happen in the following case.

FileName: LatestSwitchExpression1.java

Output:

Eleven or Twelve
Thirteen or Fourteen
The number is invalid.
Fifteen or Seventeen or Nineteen
The number is invalid.

Returning Values Via Break

Now the switch can be treated as an expression, also known as the value breaks. After the break keyword, we can put a value. Observe the following example.

FileName: LatestSwitchExpression2.java

Output:

Eleven or Twelve
Thirteen or Fourteen
The number is invalid.
Fifteen or Seventeen or Nineteen
The number is invalid.

Note: The above program will not compile with the approach we follow to compile the program that contains the traditional switch expressions. For the compilation process, use the following command.

javac --enable-preview --release 12 filename.java

After the compilation process, use the following command to run the program.

java --enable-preview filename






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA