Learn about yield keyword added in Java 14 to support switch expressions with example.
1. yield keyword
yield
is added in Java 14, and is used inside switch expressions.
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; } }; System.out.println("Result is " + result);
2. yield vs return
A return statement returns control to the invoker of a method or constructor. A yield statement transfers control by causing an enclosing switch
expression to produce a specified value.
SwitchExpression: YieldStatement: yield Expression;
SwitchExpression
tries to find a correctYieldStatement
to transfer control to innermost enclosingyield
target.SwitchExpression
terminates normally and the value of theExpression
becomes the value of theSwitchExpression
.- If the evaluation of the
Expression
completes abruptly for some reason, then theyield
statement completes abruptly for same reason.
Drop me your questions in comments related to enhanced switch statement in Java 14.
Happy Learning !!
Leave a Reply