Course outline · 0% complete

0/29 lessons0%

Course overview →

switch

lesson 3-2 · ~5 min · 8/29

Choosing among many values

Real code constantly maps one code to one outcome: an HTTP status number to a message, a menu keypress to an action, a day number to a name. When one variable decides among many fixed options like that, a chain of else ifs gets noisy and easy to typo. switch handles it directly. Modern Java (14+) has a clean arrow form:

String day = switch (dayNumber) {
  case 1 -> "Monday";
  case 2 -> "Tuesday";
  case 6, 7 -> "Weekend";
  default -> "Unknown";
};

Each case value -> picks one branch, default catches everything else, and the whole switch can produce a value you assign. You will also meet the older colon-and-break form in legacy code, where forgetting break makes execution fall through into the next case. Prefer arrows in new code.

What switch can and cannot switch on

switch works on int, char, String, and enums — types whose values are a set of fixed labels the compiler can compare exactly. It does not work on double (0.1 + 0.2 lands near 0.3, never exactly on a case) and it cannot express ranges: score >= 90 has no case form, so grading bands stay with if/else if.

String role = switch (command) {
  case "add", "a" -> "adding";
  case "quit", "q" -> "quitting";
  default -> "unknown command";
};

Decision rule: exact labels → switch, ranges or compound conditions → if.

Code exercise · java

Run the day-name switch. Then change dayNumber to 7 and to 9 and watch which case fires. Set it back to 3 to finish.

Quiz

In the old colon-style switch, what happens if a case has no break statement?

Code exercise · java

Your turn. Write an arrow switch on the char grade that assigns a message: 'A' gives `excellent`, 'B' gives `good`, 'C' gives `passing`, anything else gives `see instructor`. Print the message. With grade = 'B' the output should be `good`.