Modern Java (11 → 25)

The features that changed how Java is written since Java 8 — var, switch expressions, text blocks, records, sealed types, pattern matching, virtual threads, sequenced collections and more, release by release.

Intermediate 2 min readLesson 7 of 14

Since Java 9, a new version ships every six months, with a long-term support (LTS) release every two years: 11, 17, 21, 25. Modern Java is much more concise than the Java 8 code many tutorials still show.

Feature timeline (highlights)

VersionNotable features
9Module system (JPMS), jshell, List.of/Map.of, private interface methods
10var for local variables
11 (LTS)HttpClient, String.isBlank/strip/lines/repeat, run single-file programs with java File.java
14Switch expressions, helpful NullPointerException messages
15Text blocks
16Records, pattern matching for instanceof, Stream.toList()
17 (LTS)Sealed classes, strong encapsulation of JDK internals
21 (LTS)Virtual threads, pattern matching for switch, record patterns, sequenced collections
22–24Unnamed variables _, Foreign Function & Memory API, stream gatherers, class-file API
25 (LTS)Compact source files and instance main methods, flexible constructor bodies, module imports, scoped values

var

Java
var users = new HashMap<String, List<User>>();   // type inferred from the right-hand side
for (var entry : users.entrySet()) { ... }

Still statically typed — only the declaration is shorter. Use it when the type is obvious from the right side; avoid it when it hides important information (var x = service.process();).

Switch expressions and pattern matching

Java
// Old: statements, fall-through, break everywhere
// New: expression, arrows, exhaustive, no fall-through
int days = switch (month) {
    case FEBRUARY -> leap ? 29 : 28;
    case APRIL, JUNE, SEPTEMBER, NOVEMBER -> 30;
    default -> {
        log.debug("31-day month {}", month);
        yield 31;                                  // 'yield' returns a value from a block
    }
};

// Pattern matching for instanceof (16)
if (obj instanceof String s && !s.isBlank()) {
    System.out.println(s.length());                // s already cast
}

// Pattern matching for switch (21), with guards
String describe(Object o) {
    return switch (o) {
        case null -> "null";
        case Integer i when i > 100 -> "big int " + i;
        case Integer i -> "int " + i;
        case String s -> "string of length " + s.length();
        case int[] arr -> "array of " + arr.length;
        default -> "something else";
    };
}

Records, sealed types and record patterns

Together they give Java algebraic data types:

Java
sealed interface Result<T> permits Ok, Err {}
record Ok<T>(T value) implements Result<T> {}
record Err<T>(String message, Throwable cause) implements Result<T> {}

String render(Result<User> r) {
    return switch (r) {
        case Ok<User>(var user) -> "Hello " + user.name();          // deconstruct the record
        case Err<User>(var msg, var cause) -> "Failed: " + msg;
    };                                                               // exhaustive: no default needed
}

// Nested record patterns
record Point(int x, int y) {}
record Line(Point from, Point to) {}
if (shape instanceof Line(Point(var x1, var y1), Point(var x2, var y2))) {
    double len = Math.hypot(x2 - x1, y2 - y1);
}

// Unnamed pattern variables (22)
case Err<User>(var msg, _) -> "Failed: " + msg;

Text blocks

Java
String sql = """
    SELECT id, name
    FROM users
    WHERE active = true
      AND created_at > ?
    ORDER BY name
    """;
// Indentation is stripped based on the closing delimiter; use \ at line end to join lines

Virtual threads (21)

Lightweight threads managed by the JVM — you can have millions. Blocking I/O no longer wastes an OS thread, so simple thread-per-request code scales like async code. See Virtual threads.

Java
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (var url : urls) executor.submit(() -> fetch(url));
}

Sequenced collections (21)

A uniform API for collections with a defined order:

Java
List<String> list = ...;
list.getFirst(); list.getLast();         // instead of list.get(list.size() - 1)
list.reversed();                         // a reversed view
LinkedHashMap<K, V> map = ...;
map.firstEntry(); map.pollLastEntry(); map.putFirst(k, v);

Other quality-of-life additions

Java
// Collection factories (9)
var set = Set.of("a", "b");
var map = Map.of("k1", 1, "k2", 2);
var big = Map.ofEntries(Map.entry("a", 1), Map.entry("b", 2));

// String helpers (11+)
"  ".isBlank();  "ab".repeat(3);  text.lines().count();  " x ".strip();
"Hi %s".formatted(name);

// Helpful NPE messages (14): "Cannot invoke "String.length()" because "user.name" is null"

// Stream improvements
stream.toList();                                   // 16
stream.takeWhile(x -> x < 10).dropWhile(...);      // 9
stream.mapMulti((x, sink) -> { ... });             // 16

// HttpClient (11)
var client = HttpClient.newHttpClient();
var res = client.send(HttpRequest.newBuilder(URI.create(url)).build(),
                      HttpResponse.BodyHandlers.ofString());

// Compact source files (25): no class declaration needed for small programs
void main() {
    IO.println("Hello, world!");
}

Upgrading tips

  • Target the latest LTS your platform supports (17 minimum for Spring Boot 3; 21+ to get virtual threads).
  • Use records for DTOs and value objects, sealed interfaces + switch for closed hierarchies, switch expressions everywhere.
  • JDK internals are strongly encapsulated since 17: old libraries using sun.misc hacks may need upgrades or --add-opens.
Key takeaways
  • LTS releases: 11, 17, 21, 25; new versions every six months.
  • var, switch expressions, text blocks and records remove most boilerplate.
  • Sealed types + records + pattern matching give exhaustive algebraic data types.
  • Virtual threads (21) make blocking code scale.
  • Sequenced collections, collection factories and String helpers simplify everyday code.