in java case swtich break scope ~ read.

Scope in switch expression

Switch expression is not very often used in everyday practice of a Java developer. So, I suppose, knowledge about this construction isn't so deep as for 'if-else' or 'for'. At least, mine... :) I have faced one interesting case and want to share it with you. Let's take a look oat the code:


    int state = ...
    ...
    List states = new ArrayList<>();
    switch (state) {
        case 0:
            Integer newState = orderState + 1;
            states.add(newState);
            break;
        case 1:
            newState = orderState + 2;
            states.add(newState);
            break;
        case 2:
            newState = orderState + 3;
            states.add(newState);
            break;
        default:
            newState = orderState + 4;
            states.add(newState);
        }
 

How do you think: is this code correct? Or may be it should looks like this:


    int state = ...
    ...
    List states = new ArrayList<>();
    switch (state) {
        case 0:
            Integer newState = orderState + 1;
            states.add(newState);
            break;
        case 1:
            Integer newState = orderState + 2;
            states.add(newState);
            break;
        case 2:
            Integer newState = orderState + 3;
            states.add(newState);
            break;
        default:
            Integer newState = orderState + 4;
            states.add(newState);
        }

Should newState be declared as a new variable in every case or not? My first intention was to answer that the second variant is correct. Seemed obvious that switch is the same as if-else, but with some more if cases inside. So we would declare a new variable in every condition branch.

But it is not correct. You should declare the variable once in a switch expression and use it after in all the case blocks. It can be explained very simply: every case ends with break, which prevents processing all subsequent cases, but break is optional. If there is no break operator, then all operators under the first case will be executed, then all operators under the second case and etc. So without break, it is a simple part of the code with the same scope, where all operators will be executed in usual order.

By the way, one more hint: { and } indicate the border of scope. Switch have one pair of {}, so there is one scope, but if-else could have one pair of {} per if and else. That is why it is possible to declare the same variable in if part and in else part.