yield keyword in Java
- Details
- Written by Nam Ha Minh
- Last Updated on 30 March 2020   |   Print Email
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:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand abstraction in Java
- Understand encapsulation in Java
- Understand inheritance in Java
- Understand polymorphism in Java
Comments