GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Switch expressions | java.evolved

Home / Language / Switch expressions
Language Beginner

Switch expressions

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Switch as an expression that returns a value — no break, no fall-through.

Switch Expressions
Code Comparison
✕ Java 8
String msg;
switch (day) {
    case MONDAY:
        msg = "Start";
        break;
    case FRIDAY:
        msg = "End";
        break;
    default:
        msg = "Mid";
}
✓ Java 14+
String msg = switch (day) {
    case MONDAY  -> "Start";
    case FRIDAY  -> "End";
    default      -> "Mid";
};
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
🎯

Returns a value

Assign the switch result directly — no temporary variable needed.

🛡️

No fall-through

Arrow syntax eliminates accidental fall-through bugs from missing break.

✅

Exhaustiveness check

The compiler ensures all cases are covered.

Old Approach
Switch Statement
Modern Approach
Switch Expression
Since JDK
14
Difficulty
Beginner
JDK Support
Switch expressions
Available

Widely available since JDK 14 (March 2020)

How it works

Switch expressions return a value directly, use arrow syntax to prevent fall-through bugs, and the compiler verifies exhaustiveness. This replaces the error-prone statement form.

Related Documentation
Switch Expressions (JEP 361) ↗
Proof
View proof source ↗
Related patterns
Language Beginner

Compact source files

Java 8
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println(
            "Hello, World!");
    }
}
Java 25
void main() {
    IO.println("Hello, World!");
}
Hover to see modern ➜
JDK 25+ →
Language Intermediate

Sealed classes for type hierarchies

Java 8
// Anyone can extend Shape
public abstract class Shape { }
public class Circle extends Shape { }
public class Rect extends Shape { }
// unknown subclasses possible
Java 17+
public sealed interface Shape
    permits Circle, Rect {}
public record Circle(double r)
    implements Shape {}
public record Rect(double w, double h)
    implements Shape {}
Hover to see modern ➜
JDK 17+ →
Language Intermediate

Record patterns (destructuring)

Java 8
if (obj instanceof Point) {
    Point p = (Point) obj;
    int x = p.getX();
    int y = p.getY();
    System.out.println(x + y);
}
Java 21+
if (obj instanceof Point(int x, int y)) {
    IO.println(x + y);
}
Hover to see modern ➜
JDK 21+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.