Sunday, May 5, 2019

Java12 new feature: Switch case enhancement


Hi All,

As we all know Java12 has been released on 19th March 19 and some interesting new features introduced by Java. Will create a separate blog for each enhancement which helps the developer community to improve their work by new enhancement.

In this blog will discuss the Switch case enhancements.

Switch case:

Older way:
switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        System.out.println(6);
        break;
    case TUESDAY:
        System.out.println(7);
        break;
    case THURSDAY:
    case SATURDAY:
        System.out.println(8);
        break;
    case WEDNESDAY:
        System.out.println(9);
        break;
}

following above code, many break statements make it unnecessarily verbose,
and this visual noise often masks hard to debug errors, where missing
break statements mean that accidental fall-thorugh occurs.

Newer way:
switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);
}

introduced a much simpler way, isn't is very easy to write.
written "case L ->" to signify that only the code to the right of the label is to be executed if the label is matched. 
The above example used multiple swicth cases in a single line,which make life of developer very easy.
Other enhacment is use of local variable inside switch block,let have a look
Older war:
switch (day) {
    case MONDAY:
    case TUESDAY:
        int temp = ...
        break;
    case WEDNESDAY:
    case THURSDAY:
        int temp2 = ...     // Why can't I call use the same temp?
        break;
    default:
        int temp3 = ...     // Why can't I call use the same temp?
}
            
                                            OR
int numLetters;
switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        numLetters = 6;
        break;
    case TUESDAY:
        numLetters = 7;
        break;
    case THURSDAY:
    case SATURDAY:
        numLetters = 8;
        break;
    case WEDNESDAY:
        numLetters = 9;
        break;
    default:
        throw new IllegalStateException("Wat: " + day);
}
Expressing this as a statement is roundabout, repetitive and error-prone.
Newer way:
int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY                -> 7;
    case THURSDAY, SATURDAY     -> 8;
    case WEDNESDAY              -> 9;
};
Now its possible to compute the value from switch.

No comments:

Post a Comment