javaswitch-statement

What is the difference between a rule switch and a regular switch in Java?


I couldn't find this question anywhere else so I figured I might as well ask it. Is it purely aesthetic? Is it faster in any way? What are the main differences between the two? By regular switch, I mean

switch(var){
    case 1:
        break;
}

and by rule switch, I mean

switch(var){
    case 1 -> {}
}

Solution

  • In the regular switch you can omit to break the execution at the end of a code block. This allows a fall-through, and you can handle several different cases with the same code.

    switch(var) {
        case 1:
          dosomething();
          break;
        case 2:
          dosomethindelse();
                // the break was forgotten
        case 3:
        case 4: // these cases shall work on the same code
          doanotherthing();
                // but the break was forgotten
        default:
          donothing();
    }
    

    This advantage is also a disadvantage since the break can easily be forgotten and then lead to difficult to spot bugs.

    Therefore the rule switch was introduced, which - by it's different syntax does not require a break and thus prevents such situations. On top of that the switch expression is an expression, which means it returns a value. You can use it like

    System.out.println( switch(x) { ... });
    

    which implies the switch not only contains a decision which branch to execute but also requires a value to be returned. Hence it can be used as

    int x = 1;
    System.out.println(
        switch (x) {
            case 1 -> "one";
            case 2 -> "two";
            default -> null;
        }
    );