Java NotesRohit’s interview study guide
Chapter 05

Null, Optional and Pattern Matching

Why null is still Java's most common crash and how modern Java helps (helpful NPE messages, Optional), then pattern matching: instanceof that binds, switch over types and records, and sealed hierarchies the compiler checks for you, Java's answer to TypeScript's discriminated unions. Every example was run with Java 25.

Try it yourself. Each example is one file: save it under the name in its caption in an empty folder and type the $ lines. Nothing needs compiling first: java File.java compiles and runs it.

6 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#null and NullPointerException

Added

Every reference variable in Java (anything that isn't one of the eight primitives like int or boolean) can hold null: "no object here". Call a method on it and you get a NullPointerException (NPE), still the most common exception in Java code. Tony Hoare, who invented null references in 1965, called them his "billion-dollar mistake".

If you come from TypeScript with strictNullChecks, this is the biggest culture shock. In TS, string and string | null are different types and the compiler stops you calling .toUpperCase() on something that might be null. Java's type system doesn't track null at all: a String variable may hold a string or null, and the compiler can't tell you which. The mental model: every reference in Java is TypeScript's T | null, with the checks turned off.

What has improved is the error. Since Java 14, an NPE says exactly which reference was null, instead of just a line number. On a line like c.address().city().toUpperCase() that used to mean guessing between three candidates.

Npe.java
record Address(String city) {}
record Customer(String name, Address address) {}

void main() {
    var customers = List.of(
            new Customer("Rohit", new Address("Toronto")),
            new Customer("Ana", null));
    for (var c : customers) {
        IO.println(c.name() + " lives in " + c.address().city().toUpperCase());
    }
}
Terminal
$ java Npe.java
Rohit lives in TORONTO
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Npe$Address.city()" because the return value of "Npe$Customer.address()" is null
	at Npe.main(Npe.java:9)
What’s happening
  1. Two records (chapter 03) hold the data: a Customer has a name and an Address. Ana's address is null, which the compiler happily accepts.
  2. For Rohit the chain works: c.address() is an Address, .city() is "Toronto", .toUpperCase() gives TORONTO.
  3. For Ana, c.address() returns null, and calling .city() on it throws. The message names the culprit: Cannot invoke "Npe$Address.city()" because the return value of "Npe$Customer.address()" is null. (Npe$Address is the record's real name: in a compact source file your types are nested inside a class named after the file.)
  4. Nothing catches the exception, so the program stops at Npe.java:9; anything after it in the loop never runs.
  5. In TypeScript with strict null checks, address: Address | null would have refused to compile c.address.city. In Java the same mistake compiles and fails at run time, which is why the habits below matter.
AdvancedFailing early with Objects.requireNonNull

An NPE deep inside a method is hard to trace back to whoever passed the null. The usual defence is to reject null at the boundary: in constructors and public methods, check the arguments and fail immediately with a clear message. Objects.requireNonNull does that in one line, and a record's compact constructor is the natural place for it.

Fail.java
import java.util.Objects;

record Customer(String name, String email) {
    Customer {
        Objects.requireNonNull(name, "name is required");
        Objects.requireNonNull(email, "email is required");
    }
}

void main() {
    IO.println(new Customer("Rohit", "rohit@example.com"));
    IO.println(new Customer("Ana", null));
}
Terminal
$ java Fail.java
Customer[name=Rohit, email=rohit@example.com]
Exception in thread "main" java.lang.NullPointerException: email is required
	at java.base/java.util.Objects.requireNonNull(Objects.java:246)
	at Fail$Customer.<init>(Fail.java:6)
	at Fail.main(Fail.java:12)
What’s happening
  1. Customer { … } with no parameter list is a compact constructor: it runs before the record's fields are assigned, so it's where you validate.
  2. The first customer passes both checks and prints with the record's generated toString(): Customer[name=Rohit, email=rohit@example.com].
  3. The second has a null email. requireNonNull throws an NPE with your message, email is required, at the moment the bad object is created, not later when someone reads the email.
  4. The stack trace shows where the bad value came from: the constructor (Fail.java:6) called from main at line 12. That's the point: the error points at the caller who passed the null.
AdvancedAnnotations: @Nullable and @NonNull

Because the compiler doesn't track null, teams add annotations that tools can check: @Nullable on things that may be null, and a default of "not null" for everything else. The standard set now is JSpecify (org.jspecify.annotations), and Spring Framework 7 / Spring Boot 4 annotate their whole API with it, so IntelliJ and checkers like NullAway warn when you pass a possibly-null value where Spring expects non-null. It's not built into javac: without a checker, the annotations are only documentation. You'll see them in Spring code from chapter 12 on.

AdvancedGotcha: unboxing null throws too

#Optional

Added

Optional<T> (Java 8) is a box that holds either one value or nothing. Its purpose is narrow and specific: a method's return type that says "the result may be missing", so the caller can't forget to handle it. findUserById returning Optional<User> is honest in a way that returning a User that's sometimes null isn't.

The mental model for a TypeScript developer: Optional<User> is User | undefined made into an object, with ?. and ?? as methods: .map(User::email) is user?.email, and .orElse("no email") is ?? "no email". Like a one-element stream, you transform it with map, filter and flatMap, and get the value out at the end.

Opt.java
record User(String name, String email) {}

Map<String, User> users = Map.of("rohit", new User("Rohit", "rohit@example.com"));

Optional<User> find(String id) {
    return Optional.ofNullable(users.get(id));
}

void main() {
    IO.println(find("rohit").map(User::email).orElse("no email"));
    IO.println(find("ana").map(User::email).orElse("no email"));
    IO.println(find("ana"));
    IO.println(find("ana").get());
}
Terminal
$ java Opt.java
rohit@example.com
no email
Optional.empty
Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.base/java.util.Optional.get(Optional.java:143)
	at Opt.main(Opt.java:13)
What’s happening
  1. find wraps a lookup that can return null: Optional.ofNullable(x) gives an empty Optional for null and a full one otherwise. (Optional.of(null) would throw.)
  2. For "rohit", the Optional holds a User; .map(User::email) turns it into an Optional<String> with the email, and .orElse unwraps it: rohit@example.com.
  3. For "ana" the Optional is empty, .map does nothing, and .orElse supplies the fallback: no email. No if (user != null) anywhere.
  4. Printing an empty Optional shows Optional.empty.
  5. The last line calls get() on an empty Optional: NoSuchElementException: No value present. get() is the trap: it's just an NPE with a different name. Use orElse, orElseGet, orElseThrow or ifPresent instead.
AdvancedorElse vs orElseGet

A classic interview question, because the difference is invisible until it costs you a database call:

Fallback.java
String loadDefault() {
    IO.println("  (loading the default from the database)");
    return "guest";
}

void main() {
    Optional<String> name = Optional.of("rohit");

    IO.println("orElse:");
    IO.println(name.orElse(loadDefault()));

    IO.println("orElseGet:");
    IO.println(name.orElseGet(() -> loadDefault()));
}
Terminal
$ java Fallback.java
orElse:
  (loading the default from the database)
rohit
orElseGet:
rohit
What’s happening
  1. The Optional holds "rohit", so neither fallback is needed.
  2. orElse(loadDefault()) is an ordinary method call: Java evaluates its argument first, so loadDefault() runs and prints its message, and then orElse throws the result away and returns rohit.
  3. orElseGet(() -> loadDefault()) takes a lambda (a Supplier), which orElseGet only calls when the Optional is empty. Here it isn't, so the database line never prints.
  4. Rule: orElse for constants (orElse("guest")), orElseGet when computing the fallback costs something. JavaScript's ?? is lazy like orElseGet; Java's orElse is not.
AdvancedWhen not to use Optional

Optional was designed for return values, and using it elsewhere makes code worse:

Don'tWhyInstead
Optional fieldsnot serialisable, extra object per field, and a field can still be null itselfa nullable field with a getter returning Optional
Optional parameterscallers must wrap arguments; null can still be passedoverloads, or a nullable parameter
Optional<List<T>>two kinds of "nothing"return an empty list
optional.isPresent() then get()it's a null check with more typingmap, orElse, ifPresentOrElse
returning null from a method declared Optionalthe one thing it exists to preventOptional.empty()

Spring Data repositories (chapter 14) follow this design: findById returns Optional<T>, and findAll returns a list that may be empty.

#Pattern matching for instanceof

Added

Old Java code is full of a three-step dance: check the type with instanceof, cast, then use. Pattern matching for instanceof (Java 16) does the check and the cast in one step and gives the result a name: if (shape instanceof Circle c) means "if it's a Circle, call it c".

The mental model is TypeScript's type narrowing: after if (typeof x === "string"), TS knows x is a string inside the block. Java's pattern variable is the same idea made explicit: the narrowed value gets a new name, typed as the narrower type, and it only exists where the test is known to have passed.

Narrow.java
String describe(Object value) {
    if (value instanceof String s && !s.isBlank()) {
        return "text: " + s.strip();
    }
    if (!(value instanceof Integer n)) {
        return "not a number: " + value;
    }
    return "number doubled: " + (n * 2);
}

void main() {
    IO.println(describe("  hello "));
    IO.println(describe("   "));
    IO.println(describe(21));
}
Terminal
$ java Narrow.java
text: hello
not a number:    
number doubled: 42
What’s happening
  1. value instanceof String s tests the type and, if it matches, declares s as a String holding the same object. No cast.
  2. && !s.isBlank() can already use s, because && only evaluates its right side when the left side was true. For " hello " both pass, and s.strip() gives text: hello.
  3. " " is a String but blank, so the first if fails. It isn't an Integer either, so the second if returns not a number: followed by the three spaces.
  4. The second if uses flow scoping: if (!(value instanceof Integer n)) return …; means that after the if, n is definitely an Integer, so it's in scope for the rest of the method. For 21, n * 2 gives number doubled: 42.
  5. The Java 6 version of this method would have had two casts, (String) value and (Integer) value, each a chance to cast to the wrong type and get a ClassCastException.
AdvancedA cleaner equals

The most common place you'll see instanceof patterns in real code is equals methods (chapter 03 explains the equals contract):

Money.java
public class Money {
    private final long cents;
    private final String currency;

    public Money(long cents, String currency) {
        this.cents = cents;
        this.currency = currency;
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof Money other
                && cents == other.cents
                && currency.equals(other.currency);
    }

    @Override
    public int hashCode() {
        return Long.hashCode(cents) * 31 + currency.hashCode();
    }

    public static void main(String[] args) {
        System.out.println(new Money(500, "CAD").equals(new Money(500, "CAD")));
        System.out.println(new Money(500, "CAD").equals(new Money(500, "USD")));
        System.out.println(new Money(500, "CAD").equals("500 CAD"));
    }
}
Terminal
$ java Money.java
true
false
false
What’s happening
  1. o instanceof Money other is false for null and for any other type, so one expression replaces the old null check, type check and cast.
  2. Same amount and currency: true. Different currency: the last comparison fails, false.
  3. Comparing with a String fails the instanceof test immediately: false, with no ClassCastException.
  4. hashCode is overridden too, because equal objects must have equal hash codes (chapter 03). A record would generate both for you.

#Switch patterns, record patterns and exhaustiveness

Added

Java 21 brought patterns into switch, and that changes how you model data. A case can now match on a type (case Circle c ->), take a record apart (case Rectangle(double w, double h) ->), add a condition (when w == h), and handle null. Combined with sealed interfaces (chapter 03), the compiler knows every possible subtype, so it can check that your switch handles them all.

For a TypeScript developer this is the familiar discriminated union: type Shape = Circle | Square | Rectangle plus a switch (shape.kind) with a never check for exhaustiveness. In Java, the union is a sealed interface, the members are records, and exhaustiveness is checked by the compiler without the never trick. It's the biggest change in how idiomatic Java looks since lambdas: instead of putting an area() method in every class, you can keep the data plain and put the logic in one switch.

Shapes.java
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}

double area(Shape shape) {
    return switch (shape) {
        case Circle c -> Math.PI * c.radius() * c.radius();
        case Square s -> s.side() * s.side();
        case Rectangle(double w, double h) when w == h -> w * w;
        case Rectangle(double w, double h) -> w * h;
    };
}

void main() {
    List<Shape> shapes = List.of(new Circle(1), new Square(2), new Rectangle(2, 3), new Rectangle(3, 3));
    for (Shape s : shapes) {
        IO.println(s + " -> " + String.format("%.2f", area(s)));
    }
}
Terminal
$ java Shapes.java
Circle[radius=1.0] -> 3.14
Square[side=2.0] -> 4.00
Rectangle[width=2.0, height=3.0] -> 6.00
Rectangle[width=3.0, height=3.0] -> 9.00
What’s happening
  1. sealed interface Shape permits Circle, Square, Rectangle says these three records are the only shapes that can ever exist. Any other class trying to implement Shape is a compile error.
  2. switch (shape) is a switch expression (it returns a value) with type patterns: case Circle c matches circles and names the value c. A circle of radius 1 has area π, printed as 3.14.
  3. case Rectangle(double w, double h) is a record pattern: it checks the type and pulls the record's components straight into w and h, no r.width() calls.
  4. when w == h is a guard: the case only matches if the condition holds. Cases are tried top to bottom, so Rectangle[width=3.0, height=3.0] takes the guarded case (9.00), and 2 × 3 falls through to the plain rectangle case (6.00).
  5. There's no default, and none is needed: the compiler knows Shape has exactly three subtypes and every one is covered. Add a fourth record to permits and this switch stops compiling until you handle it, which is exactly what you want in a large codebase.
AdvancedWhat the compiler says when a case is missing
Missing.java
sealed interface Payment permits Card, Paypal, GiftCard {}
record Card(String last4) implements Payment {}
record Paypal(String email) implements Payment {}
record GiftCard(String code) implements Payment {}

String describe(Payment p) {
    return switch (p) {
        case Card c -> "card ending " + c.last4();
        case Paypal pp -> "PayPal " + pp.email();
    };
}

void main() {
    IO.println(describe(new Card("4242")));
}
Terminal
$ java Missing.java
Missing.java:7: error: the switch expression does not cover all possible input values
    return switch (p) {
           ^
1 error
error: compilation failed
What’s happening
  1. Payment has three permitted subtypes, but the switch only handles two; GiftCard is forgotten.
  2. The compiler refuses: the switch expression does not cover all possible input values. Nothing runs, not even the Card call that would have worked.
  3. This is the payoff of sealed types: the bug is found when someone adds GiftCard, at compile time, in every switch that needs updating. With a default -> branch the compiler couldn't help you, so avoid default on sealed types.
Advancednull, guards, default and dominance

A switch over a non-sealed type (like Object) needs a default. It can also handle null explicitly; without case null, a switch on null throws an NPE, just as it always did.

Labels.java
String label(Object o) {
    return switch (o) {
        case null -> "nothing";
        case Integer i when i > 100 -> "big number " + i;
        case Integer i -> "number " + i;
        case String s -> "text of length " + s.length();
        default -> "something else: " + o.getClass().getSimpleName();
    };
}

String old(Object o) {
    return switch (o) {
        case String s -> s;
        default -> "other";
    };
}

void main() {
    for (Object o : new Object[] { 7, 250, "hello", 3.5, null }) {
        IO.println(label(o));
    }
    IO.println(old(null));
}
Terminal
$ java Labels.java
number 7
big number 250
text of length 5
something else: Double
nothing
Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:220)
	at Labels.old(Labels.java:12)
	at Labels.main(Labels.java:22)
What’s happening
  1. 7 is an Integer but fails the guard i > 100, so it takes the next case: number 7. 250 passes the guard: big number 250.
  2. "hello" matches String s: text of length 5. 3.5 is a Double, which no case names, so default handles it: something else: Double.
  3. null matches case null first: nothing. Without that case, null never reaches default.
  4. old(null) proves it: that switch has no case null, so it throws NullPointerException straight away (the trace shows the switch calling Objects.requireNonNull).
  5. Order matters: case Integer i placed above case Integer i when i > 100 is a compile error ("this case label is dominated by a preceding case label"), because the guarded case could never match. Put the specific cases first.

#Unnamed variables and patterns

Added

Sometimes a variable must be declared but you don't need it: an exception you only want to catch, a lambda parameter you ignore, a record component that doesn't matter for this case. Since Java 22, you can write _ for it. It's the same idea as _ in JavaScript destructuring conventions or Python, except that in Java _ is enforced: it can't be read.

Unnamed.java
sealed interface Payment permits Card, Paypal, GiftCard {}
record Card(String last4, int expiryYear) implements Payment {}
record Paypal(String email) implements Payment {}
record GiftCard(String code, long balanceCents) implements Payment {}

String kind(Payment p) {
    return switch (p) {
        case Card(_, int year) when year < 2026 -> "expired card";
        case Card _ -> "card";
        case Paypal _, GiftCard _ -> "wallet";
    };
}

void main() {
    var payments = List.of(new Card("4242", 2025), new Card("1881", 2029), new Paypal("rohit@example.com"), new GiftCard("XMAS", 5000));
    for (var p : payments) {
        IO.println(kind(p));
    }

    try {
        Integer.parseInt("not a number");
    } catch (NumberFormatException _) {
        IO.println("ignored a bad number");
    }

    var counts = new HashMap<String, Integer>();
    for (String word : List.of("a", "b", "a")) {
        counts.merge(word, 1, Integer::sum);
    }
    counts.forEach((_, n) -> IO.println("seen " + n + " times"));
}
Terminal
$ java Unnamed.java
expired card
card
wallet
wallet
ignored a bad number
seen 2 times
seen 1 times
What’s happening
  1. case Card(_, int year) deconstructs a Card but ignores last4: only the year matters for this case. 4242 expired in 2025 and matches the guard: expired card.
  2. case Card _ matches any other card without naming it: 1881 gives card.
  3. case Paypal _, GiftCard _ puts two patterns in one case (allowed only when neither binds a name): both print wallet. The switch is still exhaustive over the sealed Payment.
  4. catch (NumberFormatException _) says "I know this can happen and I don't need the exception object". It prints ignored a bad number.
  5. (_, n) -> … ignores the map key in a lambda that has to accept two parameters. The counts are a = 2, b = 1, so it prints seen 2 times and seen 1 times (a HashMap doesn't promise an order; chapter 07).
AdvancedPrimitive patterns: still a preview

Patterns so far match reference types. Matching primitives (instanceof int i, switch over a double with patterns) is a preview feature in Java 25 (and still a preview in Java 27), so it needs --enable-preview:

Prim.java
void main() {
    Object o = 42;
    if (o instanceof int i) {
        IO.println(i + 1);
    }
}
Terminal
$ java Prim.java
Prim.java:3: error: primitive patterns are a preview feature and are disabled by default.
    if (o instanceof int i) {
                     ^
  (use --enable-preview to enable primitive patterns)
1 error
error: compilation failed
$ java --enable-preview Prim.java
43
What’s happening
  1. Without the flag, the compiler names the feature and refuses: primitive patterns are a preview feature and are disabled by default, and suggests --enable-preview.
  2. With --enable-preview, o (an Integer holding 42) matches int i, unboxed, and i + 1 prints 43.
  3. Don't use preview features in production code: they can change in the next release, and class files compiled with them only run on that exact Java version with the flag.

#Your turn: patterns

Added
Your turn: replace the null checks

Rewrite cityOf with Optional so it has no null checks and no get(): it returns the customer's city in capitals, or UNKNOWN when the customer, the address or the city is missing.

String cityOf(Customer c) { if (c != null && c.address() != null && c.address().city() != null) return c.address().city().toUpperCase(); return "UNKNOWN"; }

Show answer
City.java
record Address(String city) {}
record Customer(String name, Address address) {}

String cityOf(Customer c) {
    return Optional.ofNullable(c)
            .map(Customer::address)
            .map(Address::city)
            .map(String::toUpperCase)
            .orElse("UNKNOWN");
}

void main() {
    IO.println(cityOf(new Customer("Rohit", new Address("Toronto"))));
    IO.println(cityOf(new Customer("Ana", null)));
    IO.println(cityOf(new Customer("Maya", new Address(null))));
    IO.println(cityOf(null));
}
Terminal
$ java City.java
TORONTO
UNKNOWN
UNKNOWN
UNKNOWN
What’s happening
  1. Optional.ofNullable(c) starts the chain; a null customer gives an empty Optional.
  2. Each map runs only if there's a value, and a map whose function returns null gives an empty Optional, so a missing address or city ends the chain quietly.
  3. Rohit has a city: TORONTO. Ana has no address, Maya's address has no city, and the last call passes null itself: all three print UNKNOWN.
  4. It's TypeScript's c?.address?.city?.toUpperCase() ?? "UNKNOWN", spelled as method calls.
Your turn: an exhaustive order status

Model an order's status as a sealed interface with records Placed, Shipped(String carrier), Delivered(int days) and Cancelled(String reason), and write a switch with no default that prints a message for each. Delivered in more than 5 days should say "late".

Show answer
Status.java
sealed interface Status permits Placed, Shipped, Delivered, Cancelled {}
record Placed() implements Status {}
record Shipped(String carrier) implements Status {}
record Delivered(int days) implements Status {}
record Cancelled(String reason) implements Status {}

String message(Status s) {
    return switch (s) {
        case Placed _ -> "We got your order";
        case Shipped(String carrier) -> "On its way with " + carrier;
        case Delivered(int days) when days > 5 -> "Delivered late, after " + days + " days";
        case Delivered(int days) -> "Delivered in " + days + " days";
        case Cancelled(String reason) -> "Cancelled: " + reason;
    };
}

void main() {
    List<Status> all = List.of(new Placed(), new Shipped("Canada Post"), new Delivered(3), new Delivered(8), new Cancelled("out of stock"));
    all.forEach(s -> IO.println(message(s)));
}
Terminal
$ java Status.java
We got your order
On its way with Canada Post
Delivered in 3 days
Delivered late, after 8 days
Cancelled: out of stock
What’s happening
  1. The sealed interface lists exactly four statuses, so the switch can be checked for completeness: no default.
  2. Record patterns pull out the fields (carrier, days, reason); Placed _ has nothing to extract.
  3. The guarded Delivered case comes first, so 8 days prints the late message and 3 days the normal one.
  4. Add a fifth status (say Returned) to permits and this switch stops compiling until you add its case.
Your turn: what does this print?

Predict the output before you run it.

Object o = 15; then switch (o) { case Integer i when i > 10 -> "big"; case Integer i -> "small"; case String s -> "text"; default -> "other"; }, printed with IO.println, then the same switch with o = 15L.

Show answer
Predict.java
String size(Object o) {
    return switch (o) {
        case Integer i when i > 10 -> "big";
        case Integer i -> "small";
        case String s -> "text";
        default -> "other";
    };
}

void main() {
    IO.println(size(15));
    IO.println(size(15L));
}
Terminal
$ java Predict.java
big
other
What’s happening
  1. 15 is autoboxed to an Integer, passes the guard i > 10, and prints big.
  2. 15L is a long literal, boxed to a Long, which is not an Integer. No case matches the type, so it prints other.
  3. The lesson: type patterns match the exact runtime class (or a subtype), and Long and Integer are unrelated classes. There's no numeric conversion in a pattern.

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.