If your program must select from one of many different actions, the "switch" structure will be more efficient than an "if ..else..." structure.
switch (expression)
{
case (expression 1):{
Java statements;
break;
}
case (expression 2): {
Java statements;
break;
}
case (expression 3):{
Java statements;
break;
}default:{
Java statements;
break;
}
}
• You MUST use a break statement after each "case" block to keep execution from "falling through" to the remaining case statements.
• Only integer or character types may be used as control expressions in "switch" statements.
• It is best to place the most often used choices first to facilitate faster execution.
• While the "default" is not required, it is recommended.
If you need to have several choices give the same responses, you need to 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;
}
}