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.

SwitchExpression:
	YieldStatement:
    	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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.