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.

tip.eps The case groups are not true blocks marked with braces. Instead, each case group begins with the case keyword and ends with the case keyword that starts the next case group. All the case groups together, however, are defined as a block marked with ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.