DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 3: Modern `switch` Expressions (Java 14+)

In Part 2, we explored the traditional switch statement and learned about case labels, fall-through, break, and default.

While the traditional switch has been part of Java since its early days, it also has a few drawbacks:

  • Forgetting a break causes accidental fall-through.
  • Returning a value requires extra variables.
  • The syntax can become verbose.
  • Some bugs are easy to introduce.

To solve these problems, Java introduced Switch Expressions.

They first appeared as a preview feature in Java 12 and Java 13, and became a standard feature in Java 14.

If you're using Java 17, Java 21, or newer, this is the recommended way to write most switch statements.


Why Was a New switch Needed?

Consider the traditional approach.

String grade = "A";
String result;

switch (grade) {

    case "A":
        result = "Excellent";
        break;

    case "B":
        result = "Good";
        break;

    case "C":
        result = "Average";
        break;

    default:
        result = "Needs Improvement";
}

System.out.println(result);
Enter fullscreen mode Exit fullscreen mode

Notice how we need:

  • a separate variable
  • multiple assignments
  • multiple break statements

Modern Java lets us write the same code much more cleanly.


What Is a Switch Expression?

A switch expression returns a value.

Instead of executing statements only, it can produce a result that can be assigned directly to a variable.

Example

String grade = "A";

String result = switch (grade) {

    case "A" -> "Excellent";
    case "B" -> "Good";
    case "C" -> "Average";
    default -> "Needs Improvement";

};

System.out.println(result);
Enter fullscreen mode Exit fullscreen mode

Output

Excellent
Enter fullscreen mode Exit fullscreen mode

Much shorter and easier to read.


New Arrow (->) Syntax

The biggest visual difference is the new arrow operator.

Traditional syntax

case "A":
    System.out.println("Excellent");
    break;
Enter fullscreen mode Exit fullscreen mode

Modern syntax

case "A" -> System.out.println("Excellent");
Enter fullscreen mode Exit fullscreen mode

The arrow automatically prevents fall-through.

No break is needed.


No More Accidental Fall-Through

Traditional switch

int day = 1;

switch (day) {

    case 1:
        System.out.println("Monday");

    case 2:
        System.out.println("Tuesday");
}
Enter fullscreen mode Exit fullscreen mode

Output

Monday
Tuesday
Enter fullscreen mode Exit fullscreen mode

The missing break caused fall-through.


Modern switch

int day = 1;

switch (day) {

    case 1 -> System.out.println("Monday");

    case 2 -> System.out.println("Tuesday");

}
Enter fullscreen mode Exit fullscreen mode

Output

Monday
Enter fullscreen mode Exit fullscreen mode

Each case is isolated.


Returning Values Directly

One of the biggest improvements is that a switch can now return a value.

Example

int marks = 90;

String grade = switch (marks / 10) {

    case 10, 9 -> "A";

    case 8 -> "B";

    case 7 -> "C";

    default -> "D";

};

System.out.println(grade);
Enter fullscreen mode Exit fullscreen mode

Output

A
Enter fullscreen mode Exit fullscreen mode

Notice that no temporary variable assignments are needed inside the switch.


Multiple Case Labels

Instead of writing

switch (day) {

    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        System.out.println("Weekday");
        break;

    default:
        System.out.println("Weekend");
}
Enter fullscreen mode Exit fullscreen mode

Modern Java allows

switch (day) {

    case 1, 2, 3, 4, 5 -> System.out.println("Weekday");

    default -> System.out.println("Weekend");

}
Enter fullscreen mode Exit fullscreen mode

Much cleaner.


Using Blocks with Arrow Cases

Sometimes one line isn't enough.

You can use a block.

String browser = "Chrome";

switch (browser) {

    case "Chrome" -> {

        System.out.println("Launching Chrome");

        System.out.println("Opening homepage");

    }

    default -> System.out.println("Unsupported Browser");
}
Enter fullscreen mode Exit fullscreen mode

The yield Keyword

Suppose a case contains multiple statements and still needs to return a value.

That's where yield comes in.

Example

String browser = "Chrome";

String company = switch (browser) {

    case "Chrome" -> {

        System.out.println("Google Browser");

        yield "Google";

    }

    case "Firefox" -> {

        System.out.println("Mozilla Browser");

        yield "Mozilla";

    }

    default -> "Unknown";

};

System.out.println(company);
Enter fullscreen mode Exit fullscreen mode

Output

Google Browser
Google
Enter fullscreen mode Exit fullscreen mode

Think of yield as the return statement for a switch expression.


switch Expression with Enum

Enums work beautifully with switch expressions.

enum Coffee {

    ESPRESSO,
    LATTE,
    CAPPUCCINO,
    AMERICANO

}
Enter fullscreen mode Exit fullscreen mode
Coffee coffee = Coffee.LATTE;

String description = switch (coffee) {

    case ESPRESSO -> "Strong";

    case LATTE -> "Creamy";

    case CAPPUCCINO -> "Foamy";

    case AMERICANO -> "Black";

};

System.out.println(description);
Enter fullscreen mode Exit fullscreen mode

Output

Creamy
Enter fullscreen mode Exit fullscreen mode

switch Expression with String

String browser = "Edge";

String engine = switch (browser) {

    case "Chrome" -> "Blink";

    case "Edge" -> "Blink";

    case "Firefox" -> "Gecko";

    case "Safari" -> "WebKit";

    default -> "Unknown";

};

System.out.println(engine);
Enter fullscreen mode Exit fullscreen mode

Output

Blink
Enter fullscreen mode Exit fullscreen mode

Exhaustive Switch

A switch expression must always return a value.

Therefore every possible path must produce a result.

Example

String color = switch (number) {

    case 1 -> "Red";

    case 2 -> "Blue";
};
Enter fullscreen mode Exit fullscreen mode

Compile-time error

The compiler complains because some values are not handled.

Adding default fixes the problem.

String color = switch (number) {

    case 1 -> "Red";

    case 2 -> "Blue";

    default -> "Unknown";

};
Enter fullscreen mode Exit fullscreen mode

Traditional vs Modern Switch

Feature Traditional Switch Switch Expression
Introduced Java 1 Java 14
Returns value ❌ No ✅ Yes
Needs break ✅ Yes ❌ No
Fall-through ✅ Yes ❌ No
Arrow syntax ❌ No ✅ Yes
Multiple labels Limited ✅ Easy
Safer ❌ Less ✅ More
Recommended for new code ❌ Mostly legacy ✅ Yes

Common Beginner Mistakes

Forgetting default

A switch expression should handle every possible value.

Always include a default unless the compiler knows all possibilities (for example, every enum constant is covered).


Using break Instead of yield

Incorrect

case "Chrome" -> {

    break;

}
Enter fullscreen mode Exit fullscreen mode

Correct

case "Chrome" -> {

    yield "Google";

}
Enter fullscreen mode Exit fullscreen mode

Remember:

  • break exits a traditional switch statement.
  • yield returns a value from a switch expression.

Mixing Old and New Syntax

Avoid writing code like

case 1 ->

    break;
Enter fullscreen mode Exit fullscreen mode

The arrow syntax already prevents fall-through.

No break is needed.


Interview Questions

Why were switch expressions introduced?

To make switch statements:

  • more concise
  • safer
  • less error-prone
  • capable of returning values

What is the purpose of yield?

yield returns a value from a block inside a switch expression.


Does arrow syntax support fall-through?

No.

Each arrow case executes independently.


Can switch expressions return objects?

Yes.

They can return any type.

Example

Student student = switch (department) {

    case "IT" -> new Student("Rajesh");

    default -> new Student("Guest");

};
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Prefer switch expressions in modern Java projects.
  • Use arrow syntax whenever possible.
  • Use yield only when a case contains multiple statements.
  • Keep each case small and readable.
  • Always include a default for non-enum switches.
  • Avoid mixing old and new switch styles.

Quick Memory Trick 🧠

Remember the word ARROW:

  • A → Arrow (->)
  • R → Returns values
  • R → Readable
  • O → One case, no fall-through
  • W → Works great in modern Java

Key Takeaways

  • Switch expressions became a standard feature in Java 14.
  • They can directly return values.
  • Arrow (->) syntax removes the need for break.
  • There is no accidental fall-through.
  • Multiple case labels can be grouped together.
  • yield returns a value from a block.
  • Switch expressions are cleaner, safer, and more readable than traditional switch statements.
  • They are the preferred choice for new Java applications.

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)