Switch... standard syntax of case
1 switch (variable to be selected) 2 {3 case value 1: Statement 1; 4 break; 5 case value 2: Statement 2; 6 break; 7 ....... 8 case value n: Statement n; 9 break; 10 default: Statement n + 1; 11 break; 12}
Switch... case is a convenient choice structure, but when using the switch, if the break is not written, some undiscoverable errors will occur.
If we do not write a break after writing a case statement, we will continue to execute the following statement in the case after executing this case statement until it ends when it encounters break or right braces.
In the example below, I omit a case, and the subsequent statement will be executed even if the condition is not met.
1 class Demo 2 {3 public static void main (String [] args) 4 {5 int a = 2; 6 switch (a) 7 {8 case 1: System. out. println ("case 1"); 9 break; 10 case 2: System. out. println ("case 2"); 11 // break; 12 case 3: System. out. println ("case 3"); 13 break; 14 default: System. out. println ("others"); 15 break; 16} 17} 18}
The execution result is as follows: