How to Use New Switch Expressions in Java 12
Although I have done some practices with Java 12 before, I was able to write now. In this post, I will tell you about something special in . Tataaaaaa :) new switch expressions.
Let’s start our topic without wasting any more time.
What does Java 12 want to do with Switch Expressions?
The purposes listed in the JEP () are the following:
- Extend switches so they can be a statement or an expression.
- Allow either “Traditional” or “Simplified” scoping/control flow behavior.
- Help prepare for instance of Pattern Matching (JEP ).
What’s being added?
- Expression label of
case L -> expression;
Instead of having to break out of different cases, you can use the new switch label written “case L ->
" to signify that only the code to the right of the label is to be executed if the label is matched. You can write cleaner and more readable code with that. Besides, you don’t have to worry about forgetting writing the break
for a statement.
An example would be:
switch (day) {
case MONDAY:
case FRIDAY:
case SUNDAY:
System.out.println(6);
break;
case TUESDAY:
System.out.println(7);
break;
case THURSDAY:
case SATURDAY:
System.out.println(8);
break;
case WEDNESDAY:
System.out.println(9);
break;
}
As you see above, this is a traditional switch statement. It turns into new switch expressions in Java 12 like below.
switch (day) {
case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
case TUESDAY -> System.out.println(7);
case THURSDAY, SATURDAY -> System.out.println(8);
case WEDNESDAY -> System.out.println(9);
}
You can also return a value from the switch statement in Java 12.
int j = switch (day) {
case MONDAY -> 0;
case TUESDAY -> 1;
default -> {
int k = day.toString().length();
int result = f(k);
break result;
}
};
Before Java 12 releases, you could not use same variable names for two entirely separate cases.
int j = switch (day) {
case MONDAY:
String temp1 = "first";
break temp1.length();
case TUESDAY:
String temp2 = "second";
break temp2.length();
default:
String defaultTemp = "none";
break defaultTemp.length();
}
The scoping can now be used in the case level, it means that you can use the same variable names for different cases.
int j = switch (day) {
case MONDAY:
String temp = "first";
break temp.length();
case TUESDAY:
String temp = "second";
break temp.length();
default:
String temp = "none";
break temp.length();
}
Note: This tutorial focuses on new switch expressions in Java 12. You can read other changes in Java 12 from . Besides, code samples are taken from .
Thank you for reading! 🙏 Your thoughts are very valuable to me. Please feel free to share. 😄
And, if you want to learn all new features added between JDK 8 and JDK 13 then check out this list of :