Why do we need break after case statements?

后端 未结 17 2061
猫巷女王i
猫巷女王i 2020-11-22 04:34

Why doesn\'t the compiler automatically put break statements after each code block in the switch? Is it for historical reasons? When would you want multiple code blocks to e

17条回答
  •  遥遥无期
    2020-11-22 04:47

    The break after switch cases is used to avoid the fallthrough in the switch statements. Though interestingly this now can be achieved through the newly formed switch labels as implemented via JEP-325.

    With these changes, the break with every switch case can be avoided as demonstrated further :-

    public class SwitchExpressionsNoFallThrough {
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int value = scanner.nextInt();
            /*
             * Before JEP-325
             */
            switch (value) {
                case 1:
                    System.out.println("one");
                case 2:
                    System.out.println("two");
                default:
                    System.out.println("many");
            }
    
            /*
             * After JEP-325
             */
            switch (value) {
                case 1 ->System.out.println("one");
                case 2 ->System.out.println("two");
                default ->System.out.println("many");
            }
        }
    }
    

    On executing the above code with JDK-12, the comparative output could be seen as

    //input
    1
    // output from the implementation before JEP-325
    one
    two
    many
    // output from the implementation after JEP-325
    one
    

    and

    //input
    2
    // output from the implementation before JEP-325
    two
    many
    // output from the implementation after JEP-325
    two
    

    and of course the thing unchanged

    // input
    3
    many // default case match
    many // branches to 'default' as well
    

提交回复
热议问题