yield keyword in Java

[393 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(); };
                  Liked Article? Please Buy me a Tea 😭



Want to Clear Java Interview? Read Java Interview Notes prepared by Us


Are You Good enough in Java?



Learn Python in a Week and Master It

Comments







Search
Need Programming Help??


Below Offers ends in












VPN Pro Secure and Fast v3.0.8 Premium Mod Apk Download

Quiz For You:

Search Tags

    what is use of yield keyword

    yield keyword introduced in which JDK