switch Statement
A switch statement is useful when you need to select one of several alternatives based on the value of an integer, a character, or a String variable. The basic form of the switch statement is this:
switch (expression)
{
case constant:
statements;
break;
[ case constant-2:
statements;
break; ] ...
[ default:
statements;
break; ] ...
}
The expression must evaluate to an int, short, byte, or char. It can’t be a long or a floating-point type.
Each grouping of code lines that starts with the case keyword and ends with a break statement is a case group. You can code as many case groups as you want or need. Each group begins with the word case, followed by a constant (usually, a numeric, character, or string literal) and a colon. Then you code one or more statements that you want executed if the value of the switch expression equals the constant. The last line of each case group is a break statement, which causes the entire switch statement to end.
The default group, which is optional, is like a catch-all case group. Its statements are executed only if none of the previous case constants matches the switch expression.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access