Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

Layman Explanation

Old switch was like filling a government form — verbose, prone to errors (missing break), and you couldn't directly get a value from it. New switch expression is like a smart vending machine — you press a button, you directly GET the result. Clean, safe, no fall-through.

Old Switch Statement (Problems)

java
QUBITS OF DPK
1// Old switch — 3 problems:
2// 1. Fall-through if break is missing
3// 2. Cannot return a value directly
4// 3. Very verbose
5
6int day = 3;
7String dayName;
8
9switch (day) {
10    case 1:
11        dayName = "Monday";
12        break;           // ⚠️ forget this = disaster!
13    case 2:
14        dayName = "Tuesday";
15        break;
16    case 3:
17        dayName = "Wednesday";
18        break;
19    default:
20        dayName = "Unknown";
21}

New Switch Expression — Arrow Syntax (Java 14+)

java
QUBITS OF DPK
1// New switch expression — clean, safe, returns value directly
2int day = 3;
3
4String dayName = switch (day) {
5    case 1 -> "Monday";
6    case 2 -> "Tuesday";
7    case 3 -> "Wednesday";
8    case 4 -> "Thursday";
9    case 5 -> "Friday";
10    default -> "Weekend";
11};
12
13System.out.println(dayName);  // Wednesday

Key Improvements

javascript
QUBITS OF DPK
11. Arrow (->) syntax — NO fall-through ever!
22. Returns value directly (it's an EXPRESSION)
33. Exhaustive — compiler forces you to handle all cases
44. Much cleaner and shorter

Multiple Labels Per Case

java
QUBITS OF DPK
1int day = 6;
2
3String type = switch (day) {
4    case 1, 2, 3, 4, 5 -> "Weekday";   // multiple labels!
5    case 6, 7           -> "Weekend";
6    default             -> "Invalid";
7};
8
9System.out.println(type);  // Weekend

Switch Expression with Blocks (yield)

When you need multiple statements in a case, use {} block with yield to return value.
java
QUBITS OF DPK
1int score = 85;
2
3String grade = switch (score / 10) {
4    case 10, 9 -> "A";
5    case 8     -> "B";
6    case 7     -> {
7        System.out.println("Just passed!");
8        yield "C";          // yield returns value from block
9    }
10    default -> {
11        System.out.println("Failed!");
12        yield "F";
13    }
14};

Switch with String (Java 7+) and Enums

java
QUBITS OF DPK
1// String switch
2String season = "Winter";
3String activity = switch (season) {
4    case "Summer"  -> "Swimming";
5    case "Winter"  -> "Skiing";
6    case "Monsoon" -> "Reading";
7    default        -> "Chilling";
8};
9
10// Enum switch
11enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
12
13Day today = Day.SAT;
14String plan = switch (today) {
15    case SAT, SUN -> "Holiday!";
16    case MON      -> "Back to work";
17    default       -> "Regular day";
18};

Pattern Matching in Switch (Java 21)

java
QUBITS OF DPK
1// Java 21 — switch with type patterns!
2Object obj = "Hello, Deepak";
3
4String result = switch (obj) {
5    case Integer i -> "Integer: " + i;
6    case String s  -> "String: " + s.toUpperCase();
7    case Double d  -> "Double: " + d;
8    default        -> "Unknown type";
9};
10
11System.out.println(result);  // String: HELLO, DEEPAK

Old vs New Switch Comparison

️ All Traps

java
QUBITS OF DPK
1// Trap 1 — yield vs return
2String result = switch (x) {
3    case 1 -> {
4        return "one";   // ❌ use yield, not return!
5        yield "one";    // ✅
6    }
7};
8
9// Trap 2 — Switch expression must be exhaustive
10String s = switch (day) {
11    case 1 -> "Monday";
12    // ❌ compile error if no default and not all values covered!
13};
14
15// Trap 3 — Old colon syntax still works (no arrow)
16// Can mix old and new but don't mix arrow and colon in same switch
17switch (x) {
18    case 1 -> "a";
19    case 2: "b"; break;  // ❌ can't mix styles!
20}

30-Second Interview Answer

"Switch expressions introduced in Java 14 solve three problems with old switch statements: fall-through risk, inability to return values directly, and verbosity. Arrow syntax (->) eliminates fall-through entirely. The switch is now an expression that returns a value directly. Multiple labels per case are supported with commas. For multi-statement cases, use block syntax with yield to return the value. Java 21 extends this with pattern matching in switch, allowing type-based case matching."

Interview Questions & MAANG-Level Answers

Q1. What problems does switch expression solve over switch statement?
Three problems solved: (1) Fall-through — old switch requires break to stop execution; forgetting it silently runs the next case. Arrow syntax completely eliminates fall-through. (2) No direct value — old switch couldn't return a value directly; you had to assign in each case. New switch IS an expression that returns a value. (3) Verbosity — old switch needed case+colon+break for each. Arrow syntax is one clean line per case.
Q2. What is the arrow (->) syntax in switch?
The arrow syntax separates the case label from the code with -> instead of :. Each arrow case is independent — no fall-through possible:
java
QUBITS OF DPK
1String result = switch (day) {
2    case MONDAY, FRIDAY -> "Work from home";
3    case SATURDAY, SUNDAY -> "Holiday";
4    default -> "Office";
5};
Multiple values can share one case with commas. The expression after -> is evaluated and returned. Can be a value, method call, or block with yield.
Q3. What is yield and when do you use it?
yield is used inside a block {} case to return a value from a switch expression:
java
QUBITS OF DPK
1String result = switch (score) {
2    case 10, 9 -> "A";
3    case 8 -> {
4        System.out.println("Good score!");  // multi-statement
5        yield "B";  // yield returns value from this block
6    }
7    default -> "C";
8};
For single-expression cases, arrow syntax suffices. yield is only needed when the case requires multiple statements before returning. return would exit the entire method, not just the switch — that's why yield exists.
Q4. What does exhaustiveness mean in switch expressions?
A switch expression MUST cover all possible input values — compiler enforces this. If you switch on an int without a default, compile error (infinitely many int values). If you switch on an enum WITH all enum constants covered, default is not needed. If you switch on a sealed class with all permitted subtypes covered, default is not needed. This is more powerful than switch statement which silently does nothing on unmatched cases.
Q5. What is pattern matching in switch (Java 21)?
Java 21 allows switching on Object with type patterns, eliminating chains of instanceof:
java
QUBITS OF DPK
1Object obj = getValue();
2String result = switch (obj) {
3    case Integer i              -> "Int: " + i;
4    case String s when s.isBlank() -> "Blank string";
5    case String s               -> "String: " + s.toUpperCase();
6    case null                   -> "null";
7    default                     -> "Other: " + obj;
8};
when clause adds conditional guards. Works beautifully with sealed classes — compiler knows all possible types and verifies exhaustiveness without needing default.