The yield keyword is added to the Java language since Java 14, for implementing switch expression.

It is used to return value from a case in a switch expression. For example:

int x = switch (dayOfWeek) {
	case MONDAY:
		yield 2;
	case TUESDAY:
		yield 3;
	case WEDNESDAY:
		yield 4;
	default:
		yield 0;
};

If the switch block is used with new form of switch label “case L ->”, the yield keyword is used to return a value in a case arm that is a block of code. For example:

int x = switch (dayOfWeek) {
	case MONDAY -> 2;

	case TUESDAY -> 3;

	case WEDNESDAY -> 4;

	case THURSDAY, FRIDAY -> 5;

	case SATURDAY, SUNDAY -> {
		// line 1..
		// line 2...
		// line 3...
		yield 8;
	}

};

Note that the code after yield can be an expression that returns a value. For example:

int days = switch (month) {
		case 1, 3, 5, 7, 8, 10, 12:
			yield 31;

		case 4, 6, 9:
			yield foo();

		case 2:
			yield (year % 4 == 0 ? 29 : 28);

		default:
			throw new IllegalArgumentException();
};

In this example, foo() is a method that returns an integer value.

See all keywords in Java.

Other Java Tutorials:

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment