Modern Java (8 to 21)

Mid-level Frequently asked 7 min

On this page

The question

What has changed in Java since Java 8?

30-second answer

Java 8 brought lambdas and streams. Later releases made data modeling shorter and safer: var in 10, switch expressions in 14, text blocks in 15, records in 16 and sealed classes in 17. Java 21 adds pattern matching for switch, record patterns, sequenced collections and virtual threads. Together, records, sealed types and pattern matching let the compiler check that a switch handles every case.

Understand it

Point as a class and as a record

Compare

By hand, Point needs private final fields, a constructor, getX() and getY(), and equals, hashCode and toString, and it can extend another class.

View as text

The same Point drawn as source code: a header line, then one row per member, each tagged by hand or generated, and a last row saying whether the type can extend another class.

Class: by hand, Point needs private final fields, a constructor, getX() and getY(), and equals, hashCode and toString, and it can extend another class. The header reads class Point, every member row is tagged by hand, and the last row reads extends another class: yes.

Record: record Point(int x, int y) is one line: the compiler generates the same fields, constructor, accessors x() and y(), equals, hashCode and toString, and makes it final. The header is the whole declaration, the member rows are dashed and tagged generated, and the last row reads extends another class: no, because it is final and extends Record.

The same Point drawn as source code: a header line, then one row per member, each tagged by hand or generated, and a last row saying whether the type can extend another class.

Class: by hand, Point needs private final fields, a constructor, getX() and getY(), and equals, hashCode and toString, and it can extend another class. The header reads class Point, every member row is tagged by hand, and the last row reads extends another class: yes.

Record: record Point(int x, int y) is one line: the compiler generates the same fields, constructor, accessors x() and y(), equals, hashCode and toString, and makes it final. The header is the whole declaration, the member rows are dashed and tagged generated, and the last row reads extends another class: no, because it is final and extends Record.

Takeaway: A record declares its components in one line, and the compiler generates the fields, constructor, accessors, equals, hashCode and toString that a class needs written by hand.

Build a sealed hierarchy and its switch

Build

Build the closed Shape hierarchy and the switch over it: put each declaration and each case where it belongs.

Drag a piece, or select it and then select a place.

  1. Empty
  2. Empty
  3. Empty
  4. Empty
  5. Empty
View as text

The drawing has three layers: a sealed interface at the top, two records below it with arrows up to the interface, and a switch at the bottom with one case under each record and no default. Build the closed Shape hierarchy and the switch over it: put each declaration and each case where it belongs.

The answers are: declares the closed set of shapes takes sealed interface Shape permits Circle, Square. A permitted shape with a radius takes record Circle(double r) implements Shape. A permitted shape with a side takes record Square(double side) implements Shape. Handles every circle takes case Circle c -> Math.PI * c.r() * c.r(). Handles every square takes case Square s -> s.side() * s.side().

The switch has one case per permitted record and no default, because the compiler knows these are the only shapes.

The drawing has three layers: a sealed interface at the top, two records below it with arrows up to the interface, and a switch at the bottom with one case under each record and no default. Build the closed Shape hierarchy and the switch over it: put each declaration and each case where it belongs.

The answers are: declares the closed set of shapes takes sealed interface Shape permits Circle, Square. A permitted shape with a radius takes record Circle(double r) implements Shape. A permitted shape with a side takes record Square(double side) implements Shape. Handles every circle takes case Circle c -> Math.PI * c.r() * c.r(). Handles every square takes case Square s -> s.side() * s.side().

The switch has one case per permitted record and no default, because the compiler knows these are the only shapes.

Takeaway: A sealed interface lists every permitted type, so a switch with one case per type needs no default, and the compiler rejects a switch that misses one.

LTS releases 8, 11, 17 and 21Java 8 brings lambdas and streams. Java 11 adds var, from release 10, and the standard HTTP client. Java 17 adds switch expressions from 14, text blocks from 15, records from 16 and sealed classes from 17. Java 21 adds pattern matching for switch, record patterns, sequenced collections and virtual threads.Java 8 LTSlambdas, streamsJava 11 LTSvar (10)HTTP client (11)Java 17 LTSswitch expressions(14)text blocks (15)records (16)sealed classes (17)Java 21 LTSpattern matching forswitchrecord patternssequencedcollectionsvirtual threads
LTS releases 8, 11, 17 and 21Java 8 brings lambdas and streams. Java 11 adds var, from release 10, and the standard HTTP client. Java 17 adds switch expressions from 14, text blocks from 15, records from 16 and sealed classes from 17. Java 21 adds pattern matching for switch, record patterns, sequenced collections and virtual threads.Java 8 LTSlambdas, streamsJava 11 LTSvar (10)HTTP client (11)Java 17 LTSswitch expressions(14)text blocks (15)records (16)sealed classes (17)Java 21 LTSpattern matching forswitchrecord patternssequencedcollectionsvirtual threads
The LTS (long-term support) releases and what each one adds

In code

record Point(int x, int y) {
    Point {                          // compact constructor
        if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
    }
}

var p = new Point(1, 2);             // var: the type is still Point
System.out.println(p);               // Point[x=1, y=2]
System.out.println(p.x());           // 1
System.out.println(p.equals(new Point(1, 2)));   // true
new Point(-1, 2);                    // IllegalArgumentException
A record: one line, validated in a compact constructor
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}

static double area(Shape shape) {
    return switch (shape) {          // a missing case is a compile error
        case Circle c -> Math.PI * c.r() * c.r();
        case Square s -> s.side() * s.side();
    };
}

static String describe(Shape shape) {
    return switch (shape) {          // record patterns and a guard
        case Circle(double r) when r == 0 -> "a point";
        case Circle(double r) -> "circle of radius " + r;
        case Square(double side) -> "square of side " + side;
    };
}

area(new Square(2));                 // 4.0
describe(new Circle(0));             // "a point"
A sealed hierarchy and switches with no default
The sealed Shape hierarchy and its switchThe sealed interface Shape permits two records, Circle and Square. A switch over Shape has one case per record, case Circle c and case Square s, and no default, because the compiler knows these are the only shapes.permitspermitscase Circle ccase Square ssealed interfaceShaperecord Circlerecord Squareswitch (shape)no default
The sealed Shape hierarchy and its switchThe sealed interface Shape permits two records, Circle and Square. A switch over Shape has one case per record, case Circle c and case Square s, and no default, because the compiler knows these are the only shapes.permitspermitscase Circle ccase Square ssealed interfaceShaperecord Circlerecord Squareswitch (shape)no default
The sealed Shape hierarchy and its switch
record Point(int x, int y) {}
record Line(Point from, Point to) {}

static int manhattan(Object o) {
    if (o instanceof Line(Point(var x1, var y1), Point(var x2, var y2))) {
        return Math.abs(x2 - x1) + Math.abs(y2 - y1);
    }
    return 0;
}
Record patterns deconstruct nested records in one test (Java 21)

Solve it

Turn a DTO (data transfer object) class into a record: what changes for its callers?

CustomerDto has three private fields, a constructor, getters, equals, hashCode and toString: 60 lines. A teammate proposes a record. Decide whether it fits, and list what callers and the class must change.

  1. List what a record gives. A canonical constructor, accessors named after the components, value-based equals, hashCode and toString, and final fields.
  2. List what it forbids. No setters, no other instance fields, and it cannot extend a class. A JPA (Jakarta Persistence API) entity needs mutability and a no-arg constructor, so it stays a class.
  3. Move validation and copies. Checks go in a compact constructor; a List component gets List.copyOf there so the record stays immutable.
  4. Update callers. getName() becomes name(). Jackson 2.12+ serializes records without annotations.
  5. Check behavior that changes. Equality is now by value, so two DTOs with the same data collapse in a Set.
record CustomerDto(String name, String email, List<String> tags) {
    CustomerDto {
        Objects.requireNonNull(name, "name");
        if (email == null || !email.contains("@")) throw new IllegalArgumentException("invalid email");
        tags = List.copyOf(tags);                  // keeps the record immutable
    }
}

CustomerDto dto = new CustomerDto("Ana", "ana@example.com", List.of("vip"));
String n = dto.name();                             // was getName()
A DTO as a record: validation and a copy in the compact constructor

How to answer

  • var (Java 10) infers a local variable's type from its initializer; the type is still static.
  • Switch expressions (Java 14) return a value, and their -> arms do not fall through.
  • Records (Java 16) generate the constructor, accessors, equals, hashCode and toString from one line.
  • Sealed classes (Java 17) fix the list of subtypes, so a switch over them can omit default.
  • Java 21 finalized pattern matching for switch, record patterns, sequenced collections and virtual threads.

Common mistakes

  • Calling var dynamic typing; the compiler fixes the type at the declaration.
  • Saying a record is deeply immutable; a List component can still change through its accessor.

Follow-up questions

What is a record, and how is it different from a regular class?

A record, final in Java 16, is a class whose state is exactly its components. From record Point(int x, int y) the compiler generates private final fields, a canonical constructor, the accessors x() and y(), and equals, hashCode and toString based on the components. A record is implicitly final and extends java.lang.Record, so it cannot extend another class, but it can implement interfaces and add methods.

  • new Point(1, 2).equals(new Point(1, 2)) is true, and toString() gives Point[x=1, y=2].
  • Accessors are named after the components, x(), not getX().
  • An instance field beyond the components fails with "field declaration must be static".
  • Immutability is shallow: a List component can still change unless the constructor copies it with List.copyOf.

See it in the infographic: Point as a class and as a record

What do sealed classes and pattern matching for switch give you together?

A sealed type lists its permitted subtypes, as in sealed interface Shape permits Circle, Square, and each must be final, sealed or non-sealed; records are implicitly final. Pattern matching for switch (Java 21) tests the type and binds a variable in one case. Because the compiler knows every subtype, a switch with one case per type needs no default, and adding a subtype breaks every incomplete switch at compile time.

  • A missing case fails with "the switch expression does not cover all possible input values".
  • Record patterns (Java 21) take the components apart in the case: case Circle(double r) -> ....
  • A guard narrows a case: case Circle(double r) when r == 0 -> ....
  • A permitted subclass with no modifier fails with "sealed, non-sealed or final modifiers expected".
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}

static double area(Shape shape) {
    return switch (shape) {
        case Circle c -> Math.PI * c.r() * c.r();
        case Square s -> s.side() * s.side();
    };
}

See it in the infographic: Build a sealed hierarchy and its switch

When can you use var, and when should you avoid it?

var (Java 10) declares a local variable whose type the compiler infers from the initializer. It needs an initializer the compiler can type, and it is not allowed on fields, method parameters or return types. Use it when the right-hand side already shows the type, as in var names = new ArrayList<String>(). Avoid it when the reader would have to look up a method to know the type.

  • var x; and var y = null; are compile errors: there is nothing to infer a type from.
  • var on a field, a parameter or a return type fails with "'var' is not allowed here".
  • var list = new ArrayList<>(); infers ArrayList<Object>, so String s = list.get(0) does not compile.
  • var is a reserved type name, not a keyword: int var = 5; still compiles.

How do you validate the arguments of a record?

With a compact constructor: Point { if (x < 0) throw new IllegalArgumentException("negative"); }. It has no parameter list and runs before the fields are assigned. You can reassign the parameter, as in x = Math.abs(x) or members = List.copyOf(members), and the compiler assigns the fields afterward. Writing this.x = x inside it is a compile error.

Is var dynamic typing?

No. The compiler infers one static type from the initializer and fixes it, so the bytecode is the same as writing the type yourself. After var count = 1, the line count = "one" fails with "incompatible types: String cannot be converted to int". var only saves typing on a declaration; it changes nothing at runtime.

Check yourself

1. Which of these does record Point(int x, int y) {} NOT give you?
Show answers
  • A getX() method: Correct. The generated accessor is named after the component, so it is x().
  • An equals that compares x and y: Incorrect. The compiler generates equals from the components.
  • A constructor Point(int, int): Incorrect. The compiler generates the canonical constructor.
2. You add Triangle to the permits list of Shape and write its record. What happens to this switch, which has no default?
return switch (shape) {
    case Circle c -> Math.PI * c.r() * c.r();
    case Square s -> s.side() * s.side();
};
Show answers
  • It does not compile until a Triangle case is added: Correct. The compiler knows every permitted type, so the missing case is a compile error.
  • It compiles and throws an exception for a Triangle: Incorrect. The compiler finds the gap first, when the switch is compiled against the new Shape.
  • It compiles and returns 0 for a Triangle: Incorrect. A switch expression has no implicit value for an unhandled type.