Skip to content

Module 3 · Control Flow and Arrays — topic 2 of 4

switch Statements and Expressions

The classic switch statement with break and fall-through, the modern arrow form, switch expressions that return values with yield (Java 14), and switching on strings and enums.

Beginner 14 min read·Lesson 10 of 39 in Java Programming

Learning objectives

  • Write classic switch statements and explain fall-through
  • Use arrow-form cases and switch expressions
  • Switch on int, char, String and enum values

Definition

A switch selects one of several branches by comparing a value against constant case labels. A switch expression (Java 14+) produces a value and must cover every possible input.

Introduction

When a decision depends on which of several fixed values a variable has — a menu choice, a day of the week, a command word — a switch is often clearer than a long else-if chain. Modern Java has improved switch considerably: the arrow form has no fall-through, and a switch can now be an expression that produces a value.

Why it matters

Menu-driven programs, command parsers and state machines are naturally written with switch.

Forgetting break in a classic switch is a famous source of bugs; the modern form removes it entirely.

Detailed explanation

Classic statement. switch (x) { case 1: ...; break; case 2: ...; break; default: ...; }. Execution jumps to the matching label and continues until a break — if you omit it, control *falls through* into the next case.

Allowed types. int and smaller integers, char, their wrapper classes, String (compared with equals) and enums. Case labels must be compile-time constants and unique.

Arrow form (Java 14). case 1 -> ...; runs only that case — no fall-through and no break needed. Several labels can share a case: case "sat", "sun" -> .... A case body can be a single expression, a block in braces, or a throw.

switch expressions (Java 14). A switch can produce a value: String type = switch (day) { case 6, 7 -> "weekend"; default -> "weekday"; };. Inside a block, yield value; returns the value. A switch expression must be *exhaustive*: every possible input must be handled, usually with default. For enums, listing every constant is enough.

Pattern matching for switch (Java 21) lets cases test types, for example case Integer i -> ...; you will see it again with sealed types later in your Java journey.

Syntax

Java
// classic statement
switch (choice) {
case 1: System.out.println("one"); break;
default: System.out.println("other");
}
// arrow form expression (Java 14+)
int days = switch (month) {
case 2 -> leap ? 29 : 28;
case 4, 6, 9, 11 -> 30;
default -> 31;
};
  • Arrow and colon forms can't be mixed in one switch.
  • A switch expression ends with a semicolon because it is part of a statement.
  • Switching on a null String or enum throws NullPointerException (unless you use case null in Java 21).

Code examples

Classic switch and fall-through

Java
public class Classic {
public static void main(String[] args) {
int level = 2;
switch (level) {
case 3:
System.out.println("admin rights");
case 2:
System.out.println("edit rights");
case 1:
System.out.println("view rights");
break;
default:
System.out.println("no rights");
}
}
}
Output
edit rights
view rights

Deliberate fall-through: level 2 gets its own rights and everything below. Comment such code clearly.

Arrow cases on strings

Java
public class Commands {
public static void main(String[] args) {
String[] cmds = {"start", "STOP", "pause", "jump"};
for (String cmd : cmds) {
switch (cmd.toLowerCase()) {
case "start", "resume" -> System.out.println(cmd + ": running");
case "stop" -> System.out.println(cmd + ": stopped");
case "pause" -> System.out.println(cmd + ": paused");
default -> System.out.println(cmd + ": unknown command");
}
}
}
}
Output
start: running
STOP: stopped
pause: paused
jump: unknown command

More examples

switch expressions with yield

Java
public class Calendar {
static int daysIn(int month, int year) {
return switch (month) {
case 4, 6, 9, 11 -> 30;
case 2 -> {
boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
yield leap ? 29 : 28;
}
case 1, 3, 5, 7, 8, 10, 12 -> 31;
default -> throw new IllegalArgumentException("bad month " + month);
};
}
public static void main(String[] args) {
System.out.println(daysIn(2, 2024) + " " + daysIn(2, 2026) + " " + daysIn(9, 2026) + " " + daysIn(12, 2026));
char op = '*';
int a = 6, b = 7;
int result = switch (op) {
case '+' -> a + b;
case '-' -> a - b;
case '*' -> a * b;
case '/' -> a / b;
default -> 0;
};
System.out.println(a + " " + op + " " + b + " = " + result);
try {
daysIn(13, 2026);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
Output
29 28 30 31
6 * 7 = 42
bad month 13

Step-by-step explanation

  • return switch (month) { ... }; returns the value produced by the switch expression.
  • case 4, 6, 9, 11 -> 30; groups several labels in one case.
  • The February case needs several statements, so it uses a block and yield to produce its value.
  • default -> throw ... makes the switch exhaustive and rejects invalid months.
  • Switching on a char operator is a compact way to write a small calculator.

Expected output

Running “switch expressions with yield” prints exactly:

TextOutput
29 28 30 31
6 * 7 = 42
bad month 13

Practical applications

  • Menu-driven console programs
  • Command interpreters and protocol handlers
  • Mapping enum values to labels, prices or behaviour
  • State machines in games and parsers

Best practices

  • Prefer the arrow form in new code.
  • Use switch expressions to compute a value instead of assigning a variable in every case.
  • Always handle unexpected values with default — often by throwing an exception.

Common mistakes

Missing break in a classic switch

Avoid

case 1: System.out.println("one");
case 2: System.out.println("two"); break;

Prefer

case 1 -> System.out.println("one");
case 2 -> System.out.println("two");

Without break, case 1 falls through and also prints "two". The arrow form never falls through.

Non-exhaustive switch expression

Avoid

String s = switch (n) { case 1 -> "one"; case 2 -> "two"; };

Prefer

String s = switch (n) { case 1 -> "one"; case 2 -> "two"; default -> "many"; };

A switch expression must produce a value for every input, so the compiler requires a default for int.

Important notes

  • Switch expressions became standard in Java 14; pattern matching for switch became standard in Java 21.
  • String cases are case-sensitive; normalise with toLowerCase() first, as in the example.

Key takeaways

  • Classic switch falls through without break; arrow cases never do.
  • switch expressions return a value and must be exhaustive.
  • Use yield to return a value from a block inside a switch expression.

Try it yourself

  1. 1
    Write a switch expression that converts a day number (1–7) into its name.
  2. 2
    Build a menu loop with options 1–4 and 0 to exit using arrow cases.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerIn a switch expression, what does `yield` do?
Practise this topic