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 — Guarded patterns with when | java.evolved

Home / Language / Guarded patterns with when
Language Intermediate

Guarded patterns with when

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

Add conditions to pattern cases using when guards.

Pattern Matching Switch Expressions
Code Comparison
✕ Java 8
if (shape instanceof Circle) {
    Circle c = (Circle) shape;
    if (c.radius() > 10) {
        return "large circle";
    } else {
        return "small circle";
    }
} else {
    return "not a circle";
}
✓ Java 21+
return switch (shape) {
    case Circle c
        when c.radius() > 10
            -> "large circle";
    case Circle c
            -> "small circle";
    default -> "not a circle";
};
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
🎯

Precise matching

Combine type + condition in a single case label.

📐

Flat structure

No nested if/else inside switch cases.

📖

Readable intent

The when clause reads like natural language.

Old Approach
Nested if
Modern Approach
when Clause
Since JDK
21
Difficulty
Intermediate
JDK Support
Guarded patterns with when
Available

Widely available since JDK 21 LTS (Sept 2023)

How it works

Guarded patterns let you refine a type match with an additional boolean condition. This keeps all the branching logic in the switch instead of nesting if statements inside cases.

Related Documentation
Pattern Matching for switch (JEP 441) ↗
Proof
View proof source ↗
Related patterns
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+ →
Language Beginner

Type inference with var

Java 8
Map<String, List<Integer>> map =
    new HashMap<String, List<Integer>>();
for (Map.Entry<String, List<Integer>> e
    : map.entrySet()) {
    // verbose type noise
}
Java 10+
var map = new HashMap<String, List<Integer>>();
for (var entry : map.entrySet()) {
    // clean and readable
}
Hover to see modern ➜
JDK 10+ →
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+ →
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.