简体   繁体   中英

Why does switch execute (int type)cases that aren't matched?

I am a little puzzled why all cases are executed here, even the ones that aren't matched if I remove the break statement here:

int i = 0;
    switch ( i ) {
        case 0: System.out.print (i) ;
        case 1: System.out.print (i) ;
        case 2: System.out.print (i) ;
        case 3: System.out.print (i) ;
        default : System.out.print (i) ;
    }

This code prints out 5 times the value i. If I were to add a break after case 0, it just prints the value out once.

Reading the documentation and the function description in some books, i had expected it to only print the matching case.

Is this because it's somehow enumerated? I'm sorry I couldn't find a much better explanation and I've searched extensively, so I figured it has been asked before and I am no good at searching, or it's too basic.

You must enter a break command after each read, in order to exit the switch !

int i = 0;
    switch ( i ) {
        case 0: System.out.print (i) ;
        break ;
        case 1: System.out.print (i) ;
        break ;
        case 2: System.out.print (i) ;
        break ;
        case 3: System.out.print (i) ;
        break ;
        default : System.out.print (i) ;
       break ;
    }

The switch enter to where the condition is true, After that, it executes all the lines of code that comes after. Witout break it will not exit and And run the following code lines after.

In java switch statements, once it matches a case , all the case clauses after the matching clause are executed sequentially. This fall-through is the expected behavior. If you need to stop this, then break at each case so that, once a case is matched, it will execute only that case and then breaks from the switch block.

If your input does not match any of the case blocks, the default case is executed.

This is from the official javadoc

The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

Try the code with different i values and you'll see it for yourself how the switch behaves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM