Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 03 / Topic 3 of 8

Arrow switch: an expression that returns a value

An arrow switch (case value -> result) is an expression, not a statement: it produces a value you can assign directly. There is no break and no fall-through — each arm runs exactly its own code, nothing more.

int dayNumber = 6;
String dayType = switch (dayNumber) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
    default -> "Invalid day";
};
System.out.println("Day " + dayNumber + " is a " + dayType);

Output:

Day 6 is a Weekend

Commas group several labels on one arrow — this replaces the stacked-case fall-through trick from the classic form. When one arm needs more than a single expression, use a block body and yield to hand back the value:

int quantity = 12;
String tier = switch (quantity) {
    case 1, 2, 3 -> "Small order";
    default -> {
        String label = quantity >= 10 ? "Bulk order" : "Regular order";
        yield label;
    }
};
System.out.println("Quantity " + quantity + " -> " + tier);

Output:

Quantity 12 -> Bulk order

It also works on a String:

String city = "Pune";
int stdCode = switch (city) {
    case "Pune" -> 20;
    case "Mumbai" -> 22;
    case "Delhi" -> 11;
    default -> 0;
};
System.out.println(city + " STD code prefix: 0" + stdCode);

Output:

Pune STD code prefix: 020

Classic switch or arrow switch — which one?

Ask yourself Use
Does every branch just compute one value to use right away? Arrow switch expression
Does a branch need to do several things (print, change state, ask for more input)? Classic switch statement
Do several case values need the same value with no repeated code? Arrow switch (case 1, 2, 3 ->) or stacked classic cases
Could a case accidentally fall into the next one? Arrow switch removes that risk entirely

Full program: examples/02_switch_statement_and_expression.java.

Done here? The practice set for Part 3 — including the solutions — is on the part page.

Search the guide