Phase 4 · Advanced JavaModule 28~34 min read

Modern Java Language Features

Write cleaner code with var, text blocks, switch expressions, records, sealed classes, and more.

What you'll learn

Java evolves fast now — a new release every six months. This module gathers the modern features that make today's Java concise, safe, and expressive. You've met several already; here they come together, plus what's newest and how to stay current.

By the end you'll be able to:

  • Write concise code with var and text blocks
  • Use switch expressions and pattern matching (including record patterns)
  • Model data cleanly with records and sealed types
  • Debug faster with helpful NullPointerExceptions
  • Understand virtual threads and sequenced collections
  • Navigate Java versions, LTS releases, and preview features

var & text blocks

Two features cut everyday noise. var (Module 2) infers a local variable's type from its value. Text blocks (Module 3) let you write multi-line strings — JSON, SQL, HTML — without a mess of \n and quotes:

Concise.java
var names = new java.util.ArrayList<String>();  // type inferred
var count = 0;                                  // int

String html = """
    <html>
      <body>Hello, Java!</body>
    </html>
    """;
System.out.print(html);

Switch expressions & pattern matching

Modern switch (Module 4) is an expression that returns a value with no fall-through. Combined with pattern matching and sealed types, the compiler can even check that you've handled every case — so adding a new subtype turns a silent bug into a compile error:

Patterns.java
sealed interface Shape permits Circle, Rectangle { }
record Circle(double r) implements Shape { }
record Rectangle(double w, double h) implements Shape { }

static double area(Shape s) {
    return switch (s) {                     // exhaustive — no default needed
        case Circle c    -> Math.PI * c.r() * c.r();
        case Rectangle r -> r.w() * r.h();
    };
}

public class Main {
    public static void main(String[] args) {
        System.out.printf("%.2f%n", area(new Rectangle(3, 4)));
    }
}

The newest step, record patterns (Java 21), lets you match a type and pull its components apart in a single line — beautifully expressive:

RecordPattern.java
record Point(int x, int y) { }

public class Main {
    public static void main(String[] args) {
        Object obj = new Point(3, 4);

        // record pattern: match the type AND destructure it in one step
        if (obj instanceof Point(int x, int y)) {
            System.out.println("Sum = " + (x + y));
        }
    }
}

Records & sealed types

Records (Module 10) give you immutable data carriers in one line, and sealed classes/interfaces restrict who can extend them. Together they enable algebraic data types — a closed set of shapes the compiler fully understands, which is exactly what makes the exhaustive switch above possible.

Helpful NullPointerExceptions

A small but beloved improvement (Java 14+): when an NPE occurs on a chained call, the message now tells you precisely which part was null, instead of leaving you to guess:

HelpfulNpe.java
String city = user.getAddress().getCity().toUpperCase();

// If getCity() returns null, older Java said only:
//   Exception in thread "main" java.lang.NullPointerException

// Java 14+ Helpful NullPointerException tells you EXACTLY what was null:
//   Cannot invoke "String.toUpperCase()" because the return value of
//   "Address.getCity()" is null

Virtual threads & sequenced collections

Virtual threads (Module 22) are the headline feature of Java 21 — millions of cheap threads that make simple blocking code scale like complex async code. Sequenced collections (also Java 21) add a uniform way to work with the ends of ordered collections: getFirst(), getLast(), and reversed() on lists, deques, and linked sets/maps.

Java versions & staying current

Java releases every six months, but LTS (Long-Term Support) versions — 8, 11, 17, 21 — get years of updates and are what companies run in production. New features often arrive first as preview features (enabled with --enable-preview) before becoming permanent.

Modern Java, by version
Java 8Lambdas, Streams, Optional, java.time
Java 11 (LTS)var, HttpClient, single-file run
Java 17 (LTS)Records, sealed classes, text blocks, switch expressions
Java 21 (LTS)Virtual threads, pattern matching, record patterns, sequenced collections

Tip

Target a recent LTS (17 or 21) for new projects. Check the Java version your code must support — Android and some enterprise environments lag behind — and avoid preview features in production until they're finalised.

Recap & quick check

Key takeaways

  • var and text blocks remove everyday boilerplate.
  • Switch expressions + pattern matching + sealed types give exhaustive, compiler-checked branching.
  • Record patterns (Java 21) match a type and destructure it in one step.
  • Helpful NPEs pinpoint exactly which reference was null.
  • Prefer an LTS release (17/21); preview features need --enable-preview and aren't for production.

Quick check

1. What does a text block let you write easily?

2. Why does a switch over a sealed type not need a default case?

3. What do record patterns add?

4. Which are the LTS Java versions?

5. How do helpful NullPointerExceptions help?

Outstanding — you've completed Phase 4 and now write genuinely modern Java. From here, Phase 5 shifts to professional practice: testing, tooling, clean code, patterns, and beyond.