• You MUST use a "break" statement after each "case" block to keep execution from "falling through" to the remaining case statements. The "break" statement terminates the switch.
• Originally, only int, short, char or byte types could be used as control expressions in "switch" statements. But starting with Java 7, switch statements can also use string expressions. The switch statement will use the equals method of the String object to compare the strings. Watch out for case sensitivity.
•
It is best to place the most often used choices first to
facilitate faster execution.
•
While the "default" is not required, it is recommended. It is a safety net to prevent an error should the expression NOT match any of the cases.
• Notice the use of the colon after each case.
If you
want to have several choices give the same responses, you
can use the following coding style:
switch (value)
{
case (1):
case (2):
case (3): {
//The case code for 1, 2, 3
break;
}
case (4):
case (5):
case (6): {
//The case code for 4, 5, 6
break;
}
default: {
//The code for other values
break;
}
}
Example with Strings: (coursecode is a String variable)
switch (coursecode)
{
case ("B240"): {
System.out.println("Intro to Biology");
break;
}
case ("M360"): {
System.out.println("Linear Algebra");
break;
}
default: {
System.out.println("Not a course code.");
break;
}
}
|