In Java, a switch statement generally allows the application to have multiple possible execution paths based on the value of a given expression in runtime. The evaluated expression is called the selector expression which must be of type char, byte, short, int, Character, Byte, Short, Integer, String, or an enum.
- Java 14 (JEP 361) adds a new form of switch label “
case L ->” which allows multiple constants per case. - New switch expressions can yield a value for the whole switch-case block that can then be assigned to a variable in same statement.
1. Switch Expressions
In Java 14, switch expressions are a standard feature. In Java 13 and Java 12, it was added as a preview feature.
- It has the support of multiple case labels and using keyword
yieldto return value in place of oldreturnkeyword. - It also support returning value via label rules (arrow operator similar to lambda).
- If we use arraw
(->)operator, we can skipyieldkeyword as shown in isWeekDayV1_1(). - If we use colon
(:)operator, we need to useyieldkeyword as shown in isWeekDayV1_2(). - In case of multiple statements, use curly braces along with
yieldkeyword as shown in isWeekDayV2(). - In case of
enum, we can skip the default case. If there is any missing value not handled in cases, compiler will complain. In all other expression types (int, strings etc), we must providedefaultcase as well.
public class SwitchExpressions
{
public static void main(String[] argv)
{
System.out.println(isWeekDayV1_1(Day.MON)); //true
System.out.println(isWeekDayV1_2(Day.MON)); //true
System.out.println(isWeekDayV2(Day.MON)); //true
}
//1 - Return value directly
enum Day {
MON, TUE, WED, THUR, FRI, SAT, SUN
};
public static Boolean isWeekDayV1_1 (Day day)
{
Boolean result = switch(day) {
case MON, TUE, WED, THUR, FRI -> true;
case SAT, SUN -> false;
};
return result;
}
public static Boolean isWeekDayV1_2 (Day day)
{
Boolean result = switch(day) {
case MON, TUE, WED, THUR, FRI : yield true;
case SAT, SUN : yield false;
};
return result;
}
//2 - Multiple statements in case block
public static Boolean isWeekDayV2 (Day day)
{
Boolean result = switch(day) {
case MON, TUE, WED, THUR, FRI ->
{
System.out.println("It is WeekDay");
yield true;
}
case SAT, SUN ->
{
System.out.println("It is Weekend");
yield false;
}
};
return result;
}
}
2. Difference between yield and return
- A
returnstatement returns control to the invoker of a method or constructor. - A yield statement transfers control by causing an enclosing
switchexpression to produce a specified value.
SwitchExpression:
YieldStatement:
yield Expression;
In the above pseudo-code:
SwitchExpressiontries to find a correctYieldStatementto transfer control to innermost enclosingyieldtarget.SwitchExpressionterminates normally and the value of theExpressionbecomes the value of theSwitchExpression.- If the evaluation of the
Expressioncompletes abruptly for some reason, then theyieldstatement completes abruptly for same reason.
Happy Learning !!
Comments