GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — Switch expressions | java.evolved
Language
Beginner
Switch expressionsSwitch as an expression that returns a value — no break, no fall-through. 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";
};
See a problem with this code? Let us know.
Why the modern way wins
🎯
Returns a valueAssign the switch result directly — no temporary variable needed. 🛡️
No fall-throughArrow syntax eliminates accidental fall-through bugs from missing break. ✅
Exhaustiveness checkThe 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
Proof
Related patterns
Language
Beginner
Compact source filesJava 8
public class HelloWorld {
public static void main(String[] args) {
System.out.println(
"Hello, World!");
}
}
Java 25
void main() {
IO.println("Hello, World!");
}
JDK 25+
→
Language
Intermediate
Sealed classes for type hierarchiesJava 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 {}
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);
}
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. |