Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

JV
Java
0/14 completed
Beginner
Hello JavaVariables and typesControl flowMethodsArrays and strings
Intermediate
Classes and objectsInheritance and interfacesCollectionsExceptions
Advanced
GenericsLambdas and streamsRecords, enums and pattern matching
Pro
Concurrency and virtual threadsBuild tools, testing and real projects
Tracks / Java / Advanced

Records, enums and pattern matching

Java has changed a lot since its reputation for verbosity was earned. Features added between Java 14 and Java 21 (records, sealed types, pattern matching and switch expressions) let you model data concisely and safely. This is how modern Java looks.

Records: data classes in one line

A record is a class whose job is to hold data. One line gives you a constructor, accessor methods, equals, hashCode and toString:

java
public class Main {
    record Point(int x, int y) {}

    public static void main(String[] args) {
        Point p = new Point(3, 4);
        Point q = new Point(3, 4);

        System.out.println(p);                 // toString
        System.out.println(p.x() + p.y());     // accessors (no "get" prefix)
        System.out.println(p.equals(q));       // compares the values
        System.out.println(p == q);            // still different objects
    }
}
Output
Point[x=3, y=4]
7
true
false

Compare that with the 30 lines of fields, constructor, getters, equals, hashCode and toString you'd write for an ordinary class.

Records are immutable: their fields are final. You can still add validation, extra methods and static factories:

java
public class Main {
    record Money(long cents, String currency) {
        Money {                                          // compact constructor: validates
            if (cents < 0) throw new IllegalArgumentException("Negative amount");
            currency = currency.toUpperCase();
        }

        static Money of(double amount, String currency) {
            return new Money(Math.round(amount * 100), currency);
        }

        Money plus(Money other) {
            if (!currency.equals(other.currency)) throw new IllegalArgumentException("Currency mismatch");
            return new Money(cents + other.cents, currency);  // a new object: records never change
        }

        @Override
        public String toString() { return String.format("%s %.2f", currency, cents / 100.0); }
    }

    public static void main(String[] args) {
        Money price = Money.of(19.99, "usd");
        Money shipping = Money.of(5.01, "USD");
        System.out.println(price.plus(shipping));
        try {
            new Money(-1, "USD");
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }
}
Output
USD 25.00
Rejected: Negative amount

Use records for DTOs, API request/response bodies, results returned from methods, map keys, and value objects like money and coordinates.

Enums: a fixed set of values

java
public class Main {
    enum Status {
        PENDING("Waiting for payment"),
        PAID("Payment received"),
        SHIPPED("On its way"),
        DELIVERED("Delivered");

        private final String label;
        Status(String label) { this.label = label; }
        String label() { return label; }

        Status next() {
            return this == DELIVERED ? DELIVERED : values()[ordinal() + 1];
        }
    }

    public static void main(String[] args) {
        Status s = Status.PENDING;
        while (s != Status.DELIVERED) {
            System.out.println(s + ": " + s.label());
            s = s.next();
        }
        System.out.println(s + ": " + s.label());
        System.out.println(Status.valueOf("PAID").ordinal());
    }
}
Output
PENDING: Waiting for payment
PAID: Payment received
SHIPPED: On its way
DELIVERED: Delivered
1

Enums are type-safe (you can't pass "SHIPED" by mistake), can have fields and methods, and work beautifully with switch.

Pattern matching for instanceof

The old way needed a check and a cast. Now the check introduces a typed variable directly:

java
public class Main {
    static String describe(Object o) {
        if (o instanceof String s && !s.isEmpty()) {
            return "a string of length " + s.length();
        } else if (o instanceof Integer n) {
            return "an integer, doubled: " + (n * 2);
        }
        return "something else: " + o;
    }

    public static void main(String[] args) {
        System.out.println(describe("hello"));
        System.out.println(describe(21));
        System.out.println(describe(3.5));
    }
}
Output
a string of length 5
an integer, doubled: 42
something else: 3.5

Sealed types and pattern matching in switch

A sealed interface lists exactly which classes may implement it. Combined with records and switch patterns, you get something very powerful: the compiler knows every possible case, and tells you if you forget one.

java
public class Main {
    sealed interface Shape permits Circle, Rectangle, Triangle {}
    record Circle(double radius) implements Shape {}
    record Rectangle(double width, double height) implements Shape {}
    record Triangle(double base, double height) implements Shape {}

    static double area(Shape shape) {
        return switch (shape) {
            case Circle c -> Math.PI * c.radius() * c.radius();
            case Rectangle r -> r.width() * r.height();
            case Triangle t -> 0.5 * t.base() * t.height();
            // no default needed: the compiler knows these are all the cases
        };
    }

    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Rectangle(3, 4), new Triangle(6, 2) };
        for (Shape s : shapes) {
            System.out.printf("%s → %.2f%n", s, area(s));
        }
    }
}
Output
Circle[radius=1.0] → 3.14
Rectangle[width=3.0, height=4.0] → 12.00
Triangle[base=6.0, height=2.0] → 6.00

Add a Square to the permits list and every switch that doesn't handle it stops compiling. In large codebases, that's a huge safety net.

Record patterns and guards

Patterns can take records apart ("deconstruct" them) and add conditions with when:

java
public class Main {
    sealed interface Event permits Click, KeyPress, Scroll {}
    record Click(int x, int y) implements Event {}
    record KeyPress(String key, boolean shift) implements Event {}
    record Scroll(int amount) implements Event {}

    static String handle(Event e) {
        return switch (e) {
            case Click(int x, int y) when x == 0 && y == 0 -> "Clicked the corner";
            case Click(int x, int y) -> "Clicked at " + x + "," + y;
            case KeyPress(String key, boolean shift) when shift -> "Typed " + key.toUpperCase();
            case KeyPress(String key, boolean shift) -> "Typed " + key;
            case Scroll(int amount) when amount < 0 -> "Scrolled up " + (-amount);
            case Scroll(int amount) -> "Scrolled down " + amount;
        };
    }

    public static void main(String[] args) {
        Event[] events = { new Click(0, 0), new Click(40, 12), new KeyPress("a", true),
                           new KeyPress("b", false), new Scroll(-3), new Scroll(5) };
        for (Event e : events) System.out.println(handle(e));
    }
}
Output
Clicked the corner
Clicked at 40,12
Typed A
Typed b
Scrolled up 3
Scrolled down 5

This style of modelling data (records for the shapes of data, sealed interfaces for the alternatives, and switch to handle them) is sometimes called data-oriented programming.

Other modern conveniences

java
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        var scores = Map.of("Asha", 91, "Rahul", 78);             // var + immutable factory methods
        var list = List.of(3, 1, 2);
        System.out.println(list.reversed());                       // Java 21: sequenced collections
        System.out.println(list.getFirst() + " " + list.getLast());

        String report = """
            Name: %s
            Score: %d
            """.formatted("Asha", scores.get("Asha"));            // text block + formatted
        System.out.print(report);

        Object value = 42;
        String kind = switch (value) {
            case Integer i when i > 40 -> "big int";
            case Integer i -> "int";
            case String s -> "string";
            default -> "other";
        };
        System.out.println(kind);
    }
}
Output
[2, 1, 3]
3 2
Name: Asha
Score: 91
big int

Practice

  1. Create a record Student(String name, int grade) and use a stream to find the top student.
  2. Create an enum Planet with mass and radius fields and a surfaceGravity() method.
  3. Model a payment as a sealed interface with Card, Upi and Cash records, and write a switch that returns a fee for each (2% for cards, 0 for UPI, a fixed 10 for cash).
✎ Check your understanding

1.What does a record automatically provide?

2.What's the benefit of a sealed interface in a switch?

3.What does if (o instanceof String s) do?

← Lambdas and streams