3.3 The switch Statement

Determine on some course, more than a wild exposure to each chance that starts i' the way before thee.

—WILLIAM SHAKESPEARE, Coriolanus (1609)

When a multiway if-else statement has many possible outcomes, it can be hard to read. If the choice is based on the value of an integer or character expression, the switch statement can make your code easier to understand.

The switch statement begins with the keyword switch followed by a controlling expression in parentheses:

switch (Controlling_Expression)
{
. . .
}

The body of the statement is always enclosed in a pair of braces. Listing 3.5 shows a sample switch statement, whose ...

Get Java: An Introduction to Problem Solving and Programming, 8th Edition 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.