ProgrammingBackend Developer

What is a switch expression in Java, how does it differ from the classic switch, and what nuances are there in its usage?

Pass interviews with Hintsage AI assistant

Answer.

Background:

Before Java 12, the switch operator was exclusively used as a statement. With the release of Java 12/14, switch expressions were introduced, which expanded the syntax and capabilities of the operator. Switch expressions are designed for more concise and expressive code.

Problem:

The classic switch often leads to errors: a forgotten break results in fall-through, readability issues with many cases, an inability to return a result directly in the expression, and a lack of exhaustive value checking.

Solution:

A switch expression can return a value, use arrow syntax, support exhaustive checking at compile time, and handle null via default. Its syntax is:

String result = switch(day) { case MONDAY, FRIDAY -> "Workday"; case SATURDAY, SUNDAY -> "Weekend"; default -> throw new IllegalArgumentException(); };

Key features:

  • Switch has become an expression: its result can be assigned to a variable.
  • The new syntax improves readability and prevents forgotten breaks.
  • Support for multiple labels (case A, B -> ...).

Trick Questions.

Can switch work with enums, strings, and null?

It has worked with enums since Java 5 and with strings since Java 7. Null is only handled through default; otherwise, a NPE will occur.

switch(day) { // day == null default: System.out.println("null"); } // works

What happens if not all enum cases are implemented in a switch expression?

The compiler will require a default or implementation for all values. Absence of this will result in a compilation error.

Can break be used in the new type of switch expression?

In the arrow syntax, break is not needed. If using a block (case X -> { ... }), you can use yield to return a value:

int num = switch(x) { case 1 -> 10; case 2 -> { yield 20; } default -> 0; };

Common Errors and Anti-patterns

  • Omitting default when working with non-nullable types will lead to a compilation error.
  • Attempting to handle null outside default will cause a NullPointerException.
  • Using switch with excessive nesting instead of polymorphism.

Real-life Example

Negative Case

Classic switch with int without break:

switch(type) { case 1: actionA(); case 2: actionB(); // invoked for both type==1 and type==2 }

Pros:

  • Quickly written.

Cons:

  • Oversights lead to critical bugs.
  • Code is hard to read and maintain.

Positive Case

Using the new switch expression to match enums with results:

String status = switch(orderStatus) { case PAID -> "Paid"; case CANCELED -> "Canceled"; default -> "In Process"; };

Pros:

  • Exhaustive checking — fewer errors.
  • Code is compact and readable.

Cons:

  • Requires Java 14+ and knowledge of modern syntax.