Switch Expressions in Java

 Switch Expressions in Java


Java 12 introduced a new way to write switch statements using the switch expression. This feature provides a more concise syntax for writing switch statements, and it also allows for the use of new features like the yield keyword.

Example:


Before Java 12:



switch (dayOfWeek) {

    case MONDAY:

    case TUESDAY:

    case WEDNESDAY:

    case THURSDAY:

    case FRIDAY:

        System.out.println("Weekday");

        break;

    case SATURDAY:

    case SUNDAY:

        System.out.println("Weekend");

        break;

}

With Switch Expressions:



String dayType = switch (dayOfWeek) {

    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";

    case SATURDAY, SUNDAY -> "Weekend";

    default -> throw new IllegalStateException("Invalid day of week: " + dayOfWeek);

};

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...