- Example structure of a switch statement.
-
switch (int) {
case value1: // the statements to execute if literal
// value1 is equivalent
// optionally a break can be listed
case value2: // the statements to execute if literal
// value2 is equivalent
// optionally a break can be listed
// ...
case valueN: // the statements to execute if literal
// valueN is equivalent
// optionally a break can be listed
default: // the default statements to execute if
// none of the literal values matched
}
- Here is an example code fragment of a switch statement that will print the string value of the digits 0 through 9.
-
switch (number) {
case 0: System.out.println("zero");
break;
case 1: System.out.println("one");
break;
case 2: System.out.println("two");
break;
case 3: System.out.println("three");
break;
case 4: System.out.println("four");
break;
case 5: System.out.println("five");
break;
case 6: System.out.println("six");
break;
case 7: System.out.println("seven");
break;
case 8: System.out.println("eight");
break;
case 9: System.out.println("nine");
break;
default: System.out.println("Not 0 through 9");
}
- Here is an example code fragment of a switch statement that switches against a char value.
-
switch(grade) {
case 'A': System.out.println("Exellent");
break;
case 'B': System.out.println("Good");
break;
case 'C': System.out.println("Average");
break;
case 'D': System.out.println("Below Average");
break;
case 'E': System.out.println("Failed");
break;
default: System.out.println("Invalid");
}
- Here is an example code fragment of a switch statement that shows the falling policy to the right of the colon once an equivalent
value has been found.
-
switch(grade) {
case 'A':
case 'B':
case 'C': System.out.println("PASS");
break;
case 'D':
case 'F': System.out.println("FAIL");
break;
default: System.out.println("Invalid");
}