The advantage of switch expressions is to simplify syntax for making compact expressions. It is a variation of ternary operator "?" that is used in C and C++
Switch expressions has 2 alternative syntax. One is called "Case L ->", the other is called "Case L :". You can use symbol "->" or "yield" to return a value.
Next syntax pattern is classic, it was available before JDK-8 and is yet available. This pattern can't be used in expressions. It is an imperative statement.
switch (variable) {
case value1: //fall through
case value2:
result = result1;
break; //stop evaluation
case value3:
result = result2;
break; //stop evaluation
...
default:
result = resultN;
}
Using the new expression syntax require symbol "->" follow by an expression. This form do not allow fall-through but enable a list of values to be used for one or more cases.
result = switch (variable) {
case value1, value2 -> result1;
case value3 -> result2;
...
default -> resultN;
}
Using this expression syntax require symbol ":" follow by a block of code and keyword "yield". This syntax require "yield" and do not use break.
result = switch (variable) {
case value1, value2: {
...
yield result1;
}
case value3: {
...
yield result2;
}
...
default: {
...
yield resultX;
}
}
External Article: Switch Expressions
Read next: Record Classes