Skip to content

Beginner · Control flow and methods · topic 7 of 60 · 25 min

switch statements and switch expressions

Explanation

switch picks a branch by comparing one value with fixed cases. The classic form needs break, or execution falls through into the next case. Modern switch (Java 14+) uses arrows (case X ->), never falls through, can return a value as an expression, and must cover every possible case.

Classic switch statement

When one variable is compared with many fixed values, a switch is cleaner than a long if/else chain. The classic form, inherited from C, works with int, char, String and enum values.

java
String status = "SHIPPED";
switch (status) {
    case "PLACED":
        System.out.println("We have your order");
        break;
    case "SHIPPED":
        System.out.println("On the way");
        break;
    case "DELIVERED":
        System.out.println("Delivered");
        break;
    default:
        System.out.println("Unknown status");
}

Fall-through

Without break, the classic switch keeps running the NEXT case's statements too. This is called fall-through. It is sometimes used on purpose to group cases, but forgetting break is a very common bug.

java
int day = 6;
switch (day) {
    case 6:
    case 7:
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Weekday");
}

int x = 1;
switch (x) {
    case 1: System.out.println("one");     // no break!
    case 2: System.out.println("two");
    default: System.out.println("other");
}
// Prints one, two, other

Modern switch: arrows and expressions (Java 14+)

The arrow form does not fall through, can list several labels in one case, and a switch expression returns a value directly. The compiler checks that every possible value is handled: for strings and ints you need a default; for enums and sealed types, listing all constants is enough.

java
String status = "SHIPPED";
String message = switch (status) {
    case "PLACED" -> "We have your order";
    case "SHIPPED", "OUT_FOR_DELIVERY" -> "On the way";
    case "DELIVERED" -> "Delivered";
    default -> "Unknown status";
};

int days = switch (month) {
    case 4, 6, 9, 11 -> 30;
    case 2 -> {
        int d = isLeap ? 29 : 28;
        yield d;                 // yield returns a value from a block
    }
    default -> 31;
};

switch with enums

java
enum PaymentMode { UPI, CARD, NET_BANKING, COD }

static int fee(PaymentMode mode) {
    return switch (mode) {
        case UPI -> 0;
        case CARD -> 15;
        case NET_BANKING -> 10;
        case COD -> 40;
    };   // no default needed: every enum constant is covered
}

Java 21 added pattern matching for switch: case Circle c -> … matches by type, which you will meet with sealed interfaces in module 5.

Careful: switch on a String throws NullPointerException if the value is null (in the classic form and in arrow form without a "case null"). Check for null first, or, from Java 21, add case null -> …. Also, String cases are case-sensitive: "shipped" does not match "SHIPPED".
Think of it like this: The classic switch is like a row of water taps connected in a line: open one (a case) and water flows through every tap after it unless you close the valve (break). The arrow switch is like separate taps: each one gives water only for itself.
Tip: In new code prefer the arrow form. It is shorter, it cannot fall through by accident, and the compiler tells you when you forget a case.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

switch statements and switch expressions · 1/6

switch

In this lesson you will choose between many fixed options with switch.

Prefer a video by a teacher? Find free videos on “java switch expression arrow yield enhanced switch tutorial” on YouTube ↗

In real life: Delivery charges by zone

A courier company charges by delivery zone. A switch expression maps each zone to a charge, and the compiler forces the team to handle every zone when a new one is added to the enum.

java
enum Zone { LOCAL, METRO, REGIONAL, NORTH_EAST }

static int charge(Zone z) {
    return switch (z) {
        case LOCAL -> 40;
        case METRO -> 60;
        case REGIONAL -> 90;
        case NORTH_EAST -> 120;
    };
}
charge(Zone.METRO) is 60.

Practice (0/3 done)

Task 1 · Question

What does this print? int n = 2; switch (n) { case 1: System.out.print("A"); case 2: System.out.print("B"); case 3: System.out.print("C"); break; default: System.out.print("D"); }

Task 2 · Question

Which switch expression does NOT compile?

Task 3 · Practice

Write static int daysInMonth(int month, boolean leap) using a switch expression with grouped cases (case 4, 6, 9, 11 -> 30), a block with yield for February, and default -> 31 for the rest. Throw an IllegalArgumentException for months outside 1–12.

Quick quiz

Question 1

1.What happens in a classic switch case without break?

Question 2

2.Which keyword returns a value from a block inside a switch expression?

Question 3

3.Does the arrow form (case X ->) fall through?

Question 4

4.String s = null; switch (s) { case "a" -> … default -> … } gives…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What happens in a classic switch case without break?

Answer: Execution falls through into the next case

That is fall-through.

Which keyword returns a value from a block inside a switch expression?

Answer: yield

yield gives the block's value.

Does the arrow form (case X ->) fall through?

Answer: No

Arrow cases never fall through.

String s = null; switch (s) { case "a" -> … default -> … } gives…

Answer: NullPointerException

Without case null, switching on null throws NPE.

let x; switch (1) { case 1: x = 'one'; case 2: x = 'two'; break; } What is x?Related

Answer: 'two'

There is no break after case 1, so it falls through and case 2 sets x to two.

From switch, the ternary operator and lookup tables

What happens without break at the end of a case?Related

Answer: Execution falls through to the next case

That is fall-through.

From Decisions: if, else and switch

A switch case has code but no break. What happens?Related

Answer: Compile error: control cannot fall through

C# does not allow fall-through from a non-empty case (error CS0163).

From Decisions: if, else, switch and switch expressions

How do you make one switch case match both 1 and 2?Related

Answer: case 1, 2:

List several values separated by commas in one case.

From Decisions with if and switch

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Control flow and methods” before its exam: Loops: for, while, do-while and for-each, Methods: parameters, return values and overloading, Reading errors and debugging.
  2. Module 2 exam: Control flow and methods · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Arrays and strings. 60 topics left in the course before the final exam.

← Previous: Decisions: if, else and the ternary