Switch statements and expressions
1.3.2 — Switch statements and expressions
A switch selects code by matching a value against cases. This lesson uses three route numbers: 1, 2, and 3.
int routeNumber = 2; stores a whole number. A String holds text in double quotes. System.out.println(...) prints a value. Each example includes its own inputs.
A switch statement
Write the value to check in parentheses after switch. A case names a matching value. With ->, Java runs only the matching case.
default runs when none of the listed cases matches. Run the next cell with routeNumber = 2.
Handle an unmatched value
Change routeNumber to 9 in the cell above and run it again. No case matches 9, so default prints Unknown route.
Use a default when the input might be outside the listed choices.
A switch expression returns a value
A switch statement performs an action. A switch expression produces a value that you can store in a variable.
In the next cell, each arrow is followed by a String value. The selected value becomes routeName. The semicolon after the closing brace ends the variable declaration.
An expression must cover every possible input. Here, default provides the result for any other integer.
The older colon syntax
You may also see cases written with :. In this form, break exits the switch. Without it, execution can continue into the next case, called fall-through.
The arrow form above does not fall through. Run this colon-form example; its break statements keep the cases separate.
A decision inside a case
A case can contain a block in braces. Inside it, an if/else can make another decision. if runs its first branch when the boolean condition is true; otherwise else runs.
In the next cell, weatherRoute = 3 selects the Hill case. Then raining determines its message. No other case is checked after the match.
Which form should you use?
Use switch to match a value against fixed choices, such as route numbers 1, 2, and 3. Use if/else to check a condition, such as whether age >= 16.
A switch statement can print a message in each case. A switch expression gives back a value, such as "Park", which you can store in a variable.
Practice: add one route
Add case 2 -> "Park"; above default in the next cell. Keep the default. Run the cell: it should print Park.
Hint
Use the same form as case 1: a case number, ->, a quoted result, and a semicolon.
Worked solution
int practiceRoute = 2;
String practiceName = switch (practiceRoute) {
case 1 -> "River";
case 2 -> "Park";
default -> "Unknown route";
};
System.out.println(practiceName);Check each choice
In your completed practice cell, change only practiceRoute:
| practiceRoute | Expected output |
|---|---|
| 1 | River |
| 2 | Park |
| 9 | Unknown route |
In the earlier weather example, change only raining to false. Route 3 should then print Hill open.
Enable JavaScript to run the Java notebook.