yield keyword in Java

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.

    	yield Expression;
  • SwitchExpression tries to find a correct YieldStatement to transfer control to innermost enclosing yield target.
  • SwitchExpression terminates normally and the value of the Expression becomes the value of the SwitchExpression.
  • If the evaluation of the Expression completes abruptly for some reason, then the yield 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

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial