Switch expression is introduced as preview feature in Java12 and 13.
a. Java12 First preview (https://openjdk.java.net/jeps/325)
b. Java13 Second preview (https://openjdk.java.net/jeps/354)
In Java14, switch expressions are added as permanent feature (https://openjdk.java.net/jeps/361).
Switch expressions bring clear and safe code. Let us see it with an example.
Without switch expressions
switch (number) {
case 2:
System.out.println("Number is even and prime");
break;
case 3:
case 5:
System.out.println("You choosen a prime number and it is < 7");
break;
case 4:
case 6:
System.out.println("You entered even number and it is < 8.");
default:
System.out.println("You entered a number");
}
With switch expressions
String result = switch (number) {
case 2 -> "Number is even and prime";
case 3, 5 -> "You choosen a prime number and it is < 7";
case 4, 6 -> "You entered even number and it is < 8.";
default -> "You entered a number";
};
SwitchExpressionDemo1.java
public class SwitchExpressionDemo1 {
public static void main(String args[]) {
int number = 2;
// Without switch expression
switch (number) {
case 2:
System.out.println("Number is even and prime");
break;
case 3:
case 5:
System.out.println("You choosen a prime number and it is < 7");
break;
case 4:
case 6:
System.out.println("You entered even number and it is < 8.");
default:
System.out.println("You entered a number");
}
// with switch expression
String result = switch (number) {
case 2 -> "Number is even and prime";
case 3, 5 -> "You choosen a prime number and it is < 7";
case 4, 6 -> "You entered even number and it is < 8.";
default -> "You entered a number";
};
System.out.println(result);
}
}
Output
Number is even and prime
Number is even and prime
If your case statement has multiple lines, then enclose them in curly braces {} and return the last line using yield expression.
SwitchExpressionDemo2.java
public class SwitchExpressionDemo2 {
public static void main(String args[]) {
int number = 2;
String result = switch (number) {
case 2 -> {
System.out.println("For input 2");
yield "Number is even and prime";
}
case 3, 5 -> {
System.out.println("For input 3 or 5");
yield "You choosen a prime number and it is < 7";
}
case 4, 6 -> {
System.out.println("For input 4 or 6");
yield "You entered even number and it is < 8.";
}
default -> {
System.out.println("No input matched");
yield "You entered a number";
}
};
System.out.println(result);
}
}
Output
For input 2
Number is even and prime
1. As you see above snippet, value returned from switch expression is assigned to the variable ‘result’.
2. If you have multiple case statements that matches to same business logic, you can separate case conditions by comma operator.
Example
case 3, 5: yield "You choose a prime number and it is < 7";
Reference
https://openjdk.java.net/jeps/361
No comments:
Post a Comment