yield keyword in Java

[1992 views]




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

'yield' keyword is used to return value from a case in a switch expression. For example:-

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

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

int x = switch (weekDay) { case MONDAY -> 2; case TUESDAY -> 3; case WEDNESDAY -> 4; case THURSDAY -> 5; case SATURDAY, SUNDAY -> { // line 1.. // line 2... // line 3... yield 7; } };

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 myMethod(); case 2: yield (year % 4 == 0 ? 29 : 28); default: throw new IllegalArgumentException(); };
                 



Clear Any Java Interview by Reading our Ebook Once.


Can you clear Java Interview?



Comments










Search

Hot Deals ends in













Technical Quizzes Specially For You:

Search Tags

    what is use of yield keyword

    yield keyword introduced in which JDK