break and switch appears to execute all case statements

前端 未结 4 1807
南笙
南笙 2020-12-21 02:45

In the latest stable release of Java and Eclipse (Kempler), entering the following code and executing it, assuming the package and class names exist:

package         


        
相关标签:
4条回答
  • 2020-12-21 02:53

    The reason why switch works as it does is that this:

    switch(p){  
            case (1):
                x--;
            case (2):
                x = 2;
            case (3):
                x = 3;
            default:
                x++;
        }
    

    is really just syntactic sugar for this (basically):

    if (p == 1)
        goto .L1;
    else if (p == 2)
        goto .L2;
    else if (p == 3)
        goto .L3;
    else
        goto .L4;
    
    .L1:
        x--;
    .L2:
        x = 2;
    .L3:
        x = 3;
    .L4:
        x++;
    

    Java doesn't have a goto statement, but C does, and that's where it comes from. So if p is 2, it jumps to .L2 and executes all the statements following that label.

    0 讨论(0)
  • 2020-12-21 03:04

    When you don't put a break the switch will execute all other cases that are underneath the entry point

    So it actually executes

     x = 2;
     x = 3;
     x++;
     print(x);
     System.out.println(x);
    

    Tks to Pshemo here is a link to the specification of the switch statement

    0 讨论(0)
  • 2020-12-21 03:07

    If you want to skip all following cases you need to put a break; at last of this case block or all following case blocks are executed, too.

    Have a look: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

    0 讨论(0)
  • 2020-12-21 03:12

    If a condition in a case block is true and there is no return or break, all the other case blocks will be executed regardless if the are true or not.

    For a rule of thumb always put a break or return at the end of a case block and you will be 90% right.

    switch (p) {
        case (1):
            x--;
            break;
        case (2):
            x = 2;
            break;
        case (3):
            x = 3;
            break;
        default:
            x++;
            break;
    }
    
    0 讨论(0)
提交回复
热议问题