java 12 and 13 introduced Switch expression as a preview feature .
Java 14 introduce JEP 361: Switch Expressions as a standard feature.
Wit this version, Switch expressions are supported without –enable-preview
flag for javac and java tools.
Now,It supports Statements and expressions with Switch case syntax. Java 14 introduced below
- Switch case label
case value -> expression
, that allows multiple values separated by commas - Switch expression values are evaluated and yield an value and assigned to an variable
Switch Expressions Standard feature
Let’s see an examples
- Switch expressions assigned to an variable
Below example variable declared, assigned with Switch expression
public class java12expression {
public static void main(String[] args) {
String number = "one";
String result = switch (number) {
case "one" -> "one";
case "two" -> "two";
case "three" -> "three";
case "four" -> "four";
case "five" -> "five";
default -> "Default";
};
System.out.println(result); // printed one
}
}
- Switch expressions contains new case label syntax
It contains case L -> label syntax
case left side -> rightside
left side contains label(s), multiple labels are separated by comma.
Right side is an expression
or throw
or block
statements.
The above examples contains an case statements such as case "one"-> "one"
- Multiple labels or constants for each case
public class java12expression {
public static void main(String[] args) {
int number = 9;
String result = switch (number) {
case 2, 4, 6, 8, 10 -> "even";
case 1,3,5,7,9-> "odd";
default -> " other numbers";
};
System.out.println("result " + result);
}
}
Switch expression Rules and notes
- Multiple case labels are separated by comma
- yield keyword used to return value instead of return
- If arraw (->) operator is used, Default it returns a value without yield keyword
- if case contains
:
operator, yiled keyword used to return a value. - Inside Case body, multiple statements are declared using
{}
. - Default is not required incase of enum constants.