The switch branch in Java is one of the conditional judgments in Java, and another category belongs to If...else, and here are some of the features of the switch branch
First, format
Switch (value) {Case value 1: statement; break; Case value 2: statement in the case of the ; break; ...... Default : statement n;}
The value after the ①, case, is a specific value: number, character, string
②, end of the flag: one is encountered break statement, one is the code execution to the last position, that is, the end of the switch code
Second, case penetrating
When there is no break in the case statement, the program does not judge the value of the next sentence and executes the code statement for the next case until the break stops
Package Com.test.shuzu;public class Switch02 {public static void main (string[] args) {switch_02 ();} private static void switch_02 () {int a = ' s '; switch (a) {case ' s ': System.out.println ("s"), case ' s ': System.out.println ("s") Case ' a ': System.out.println ("a");d efault:System.out.println ("Default");}}
Execution Result:
S
S
A
Default
Third, default statement
The default statement has its particularity throughout the switch branch.
First, the default statement can be placed at the end of the switch, but it is important to note that if default is to be added in other locations, the break statement will cause case penetration.
Second, if the default is at the end, there is no need to add a break;
The default statement can then be thought of as another case statement, and the default statement is executed when the others do not meet the criteria
Package Com.test.shuzu;public class Switch01 {public static void main (string[] args) {switch_01 ();} private static void switch_01 () {int a = ' s '; switch (a) {case ' s ': System.out.println ("s"); Break;case ' a ': System.out.print ln ("a"); Break;default:system.out.println ("Default");}}}
Execution result is: Default
Finally, regardless of where the default is located, the code always executes all the case statements and the last executed default statements;
Switch branches in Java note points