Why do we need break after case statements?

后端 未结 17 2243
猫巷女王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:53

    Java comes from C and that is the syntax from C.

    There are times where you want multiple case statements to just have one execution path. Below is a sample that will tell you how many days in a month.

    class SwitchDemo2 {
        public static void main(String[] args) {
    
            int month = 2;
            int year = 2000;
            int numDays = 0;
    
            switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    numDays = 31;
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    numDays = 30;
                    break;
                case 2:
                    if ( ((year % 4 == 0) && !(year % 100 == 0))
                         || (year % 400 == 0) )
                        numDays = 29;
                    else
                        numDays = 28;
                    break;
                default:
                    System.out.println("Invalid month.");
                    break;
            }
            System.out.println("Number of Days = " + numDays);
        }
    }
    

提交回复
热议问题