Java Roadmap

From your first java Hello.java to a production Spring Boot service: types, strings, control flow, classes and exceptions, then object-oriented design with interfaces, records, enums and sealed types, generics, collections, lambdas and streams, files, Maven and JUnit, then concurrency and virtual threads, how the JVM and garbage collector work, JDBC and HTTP, and finally Spring Boot with JPA, security, Testcontainers, metrics and containers. 42 topics in four stages, each with what to learn, free resources, a practice task and, for most, a tested example and Exercism exercises. Tick things off as you go; your progress is saved in this browser. Use the filter to follow the Core Java path, the Spring backend path or the OCP Java SE 25 exam path.

Written for Java 25, the current long-term support (LTS) release (25.0.5, October 2026); everything also applies to Java 26 and 27, and the newest features are pointed out. Every Java example on this page was compiled and run on JDK 25 in November 2026, the Spring examples were built and tested together as one Spring Boot 4.1 app, and every link was checked.

The roadmap in detail

Everything from the map above, on one page. Dashed topics are optional. The hours are rough estimates for reading plus hands-on practice. Everything here is free: the JDK, Maven, Gradle, Spring, IntelliJ IDEA's free edition, VS Code and every exercise and resource linked.

Stage 1 · Beginner Java fundamentals

Install a JDK, run your first program and learn the core language: types, strings, control flow, arrays, methods, classes and exceptions. By the end of this stage you can write small command-line programs and solve beginner exercises without looking things up every minute.

What Java is and where it's used

Java is a general-purpose, statically typed, object-oriented language that compiles to bytecode. The bytecode runs on the Java Virtual Machine (JVM), which compiles the hot parts to machine code while your program runs. That is where "write once, run anywhere" comes from: the same .class or .jar file runs on Linux, Windows and macOS, on x64 and ARM.

Java runs a huge share of the world's backend systems: banks, payment networks, e-commerce, Kafka, Elasticsearch, Hadoop and Spark, Minecraft servers, and Android apps (through the Kotlin and Java ecosystem). Its strengths are a big standard library, excellent tooling, strong backwards compatibility and a fast, mature runtime. A new Java version ships every six months (March and September); every two years one of them is a long-term support (LTS) release that companies standardise on.

Java is free. OpenJDK is the open-source reference implementation, and several vendors ship free, tested builds of it: Eclipse Temurin, Amazon Corretto, Microsoft Build of OpenJDK, Azul Zulu, Red Hat and Oracle's own OpenJDK builds. Oracle JDK is a separate product with its own licence.

What to learn

  • Source code → javac → bytecode (.class) → the JVM runs it
  • JDK vs JRE vs JVM, and why you install a JDK
  • The release cadence: a feature release every six months, an LTS every two years (21, 25, next 29)
  • Where Java is used: backend services, data platforms, Android, enterprise apps
  • OpenJDK builds you can use for free, and why Oracle JDK's licence is different

Free resources

Practice

Write three sentences for a friend: what the JVM does, why a Java program built on Windows runs on a Linux server, and which JDK version you'd pick for a new project today and why.

Install a JDK and run your first program

Install JDK 25, the current LTS, from Adoptium (Eclipse Temurin), your Linux package manager or a version manager such as SDKMAN!. Check it with java -version.

Since Java 25 a first program is tiny. A compact source file can hold a bare void main() method, and the new IO class prints and reads lines. You don't even need to compile first: java Hello.java compiles in memory and runs. Later you'll see the classic public static void main(String[] args) inside a class; it still works and is what larger programs use. For trying single lines, use jshell, Java's interactive shell.

// Hello.java  —  run it with:  java Hello.java
void main() {
    IO.println("Hello, Java!");          // prints Hello, Java!
    String name = "Ada";
    IO.println("Hi " + name + ", 2 + 3 = " + (2 + 3));
    // prints Hi Ada, 2 + 3 = 5
}
java -version          # openjdk version "25.0.5" … LTS
java Hello.java        # compile in memory and run
javac Hello.java       # or compile to Hello.class first…
java Hello             # …and run the class
jshell                 # interactive: try  "abc".length()

What to learn

  • Install JDK 25 and check java -version and javac -version
  • Run a compact source file with java Hello.java
  • Compile with javac and run the .class file
  • The classic entry point: public static void main(String[] args)
  • Try expressions in jshell (/vars, /exit)
  • Set up an IDE: IntelliJ IDEA (free), VS Code with the Java extensions or Eclipse

Free resources

Practice

Install JDK 25, run the Hello example both ways (java Hello.java and javac + java), then change it to ask for your name with IO.readln("Name? ") and greet you. Open the same file in your IDE and run it from there.

Variables, types and operators

Every Java variable has a type, checked when you compile. There are eight primitive types: int and long for whole numbers, double and float for decimals, boolean, char, byte and short. Everything else (strings, lists, your own classes) is a reference type: the variable holds a reference to an object, or null.

var lets the compiler infer a local variable's type; the variable is still statically typed. Watch for the classic traps: integer division (7 / 2 is 3), overflow (int silently wraps past about 2.1 billion), and double rounding (0.1 + 0.2 is not exactly 0.3; use BigDecimal for money).

import java.math.BigDecimal;

void main() {
    int apples = 7;
    long population = 8_100_000_000L;   // too big for int
    double price = 2.50;
    boolean inStock = apples > 0;
    var label = "apples";                // inferred: String

    IO.println(apples / 2);              // prints 3
    IO.println(apples / 2.0);            // prints 3.5
    IO.println(apples % 2);              // prints 1
    IO.println(Integer.MAX_VALUE + 1);   // prints -2147483648
    IO.println(0.1 + 0.2);               // prints 0.30000000000000004
    IO.println(new BigDecimal("0.1").add(new BigDecimal("0.2")));
    // prints 0.3
    IO.println(inStock && price < 3 ? "buy " + label : "skip");
    // prints buy apples
    IO.println((int) 3.99);              // prints 3
    IO.println(population);              // prints 8100000000
}

What to learn

  • The eight primitive types, their sizes and default values
  • Literals: 1_000_000, 10L, 2.5f, 'c', 0xFF
  • Arithmetic, comparison, logical (&&, ||, !) and ternary operators; operator precedence
  • Widening and narrowing conversions, casts, integer division and overflow
  • var for local variables, final for values that never change
  • Wrapper classes (Integer, Double…), autoboxing and why == on them is a trap
  • BigDecimal for money, Math for common functions

Free resources

Practice

Write a tip calculator: read a bill amount and tip percentage, print the tip and total with two decimals. Do it once with double and once with BigDecimal and find an input where the double version prints a surprising result.

Strings and text

A String is an immutable sequence of characters: methods like toUpperCase() or replace() return a new string and never change the old one. Compare strings with equals(), never == (which compares references). Build long strings in a loop with StringBuilder.

Modern Java adds text blocks (""") for multi-line text such as JSON or SQL, formatted() for printf-style formatting, and handy methods like isBlank(), strip(), repeat() and lines().

void main() {
    String s = "  Hello, World  ";
    String t = s.strip();
    IO.println(t.toUpperCase());              // prints HELLO, WORLD
    IO.println(t.length() + " " + t.indexOf("World"));  // prints 12 7
    IO.println(t.substring(0, 5));            // prints Hello
    IO.println(t.contains("World"));          // prints true
    IO.println(String.join("-", "a", "b", "c"));  // prints a-b-c

    String a = "java", b = new String("java");
    IO.println((a == b) + " " + a.equals(b)); // prints false true

    var sb = new StringBuilder();
    for (int i = 1; i <= 3; i++) sb.append(i).append(',');
    IO.println(sb.reverse());                 // prints ,3,2,1

    String json = """
        {"name": "%s", "age": %d}""".formatted("Ada", 36);
    IO.println(json);                // prints {"name": "Ada", "age": 36}
    IO.println("%.2f%%".formatted(12.345));   // prints 12.35%
}

What to learn

  • Immutability, the string pool, and equals() vs ==
  • Common methods: length, charAt, substring, indexOf, split, replace, strip, isBlank
  • StringBuilder for building text in loops
  • Text blocks and formatted() / String.format placeholders
  • char, Character helpers and converting between strings and numbers (Integer.parseInt, String.valueOf)
  • Unicode basics: why length() counts UTF-16 units, not letters

Free resources

Practice

Write a program that reads a sentence and prints: the word count, the longest word, the sentence with every word capitalised, and whether it is a palindrome when you ignore spaces, punctuation and case.

Control flow: if, loops and switch

Java has the usual if/else, while, do/while, the counting for loop and the enhanced for (for-each) loop, plus break and continue.

Prefer the modern switch expression with arrow labels: it returns a value, needs no break (so no accidental fall-through), and the compiler tells you when you forgot a case for an enum or sealed type. Use yield to return a value from a block inside it.

void main() {
    for (int i = 1; i <= 15; i++) {
        String out = i % 15 == 0 ? "FizzBuzz"
                   : i % 3 == 0 ? "Fizz"
                   : i % 5 == 0 ? "Buzz"
                   : String.valueOf(i);
        if (i >= 13) IO.println(out);   // 13, 14, FizzBuzz
    }
    // prints 13
    // prints 14
    // prints FizzBuzz

    String day = "SAT";
    int hours = switch (day) {
        case "SAT", "SUN" -> 0;
        case "FRI" -> 6;
        default -> {
            int base = 8;
            yield base;
        }
    };
    IO.println(day + ": " + hours + "h");   // prints SAT: 0h

    int n = 27, steps = 0;
    while (n != 1) {
        n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
        steps++;
    }
    IO.println("Collatz steps: " + steps);  // prints Collatz steps: 111
}

What to learn

  • if / else if / else and the ternary operator
  • while, do/while, for and the enhanced for-each loop
  • break, continue and labelled breaks for nested loops
  • Switch expressions with ->, multiple labels and yield
  • The old switch statement with case: and fall-through (you'll read it in older code)

Free resources

Practice

Build a number-guessing game: the program picks a random number from 1 to 100, reads guesses with IO.readln, answers "higher" or "lower", and prints how many tries it took. Use a switch expression to turn the try count into a rating.

Arrays

An array is a fixed-size block of values of one type, indexed from 0. Its length is set when you create it and never changes; reading past the end throws ArrayIndexOutOfBoundsException. The Arrays class sorts, searches, fills, copies and prints them. Most everyday code uses List instead (stage 2), but arrays are still used for main's arguments, performance-sensitive code, grids and many exercises.

import java.util.Arrays;

void main() {
    int[] scores = {72, 95, 58, 88};
    int total = 0;
    for (int s : scores) total += s;
    IO.println("avg " + total / scores.length);    // prints avg 78

    int[] sorted = scores.clone();
    Arrays.sort(sorted);
    IO.println(Arrays.toString(sorted));   // prints [58, 72, 88, 95]
    IO.println(Arrays.toString(scores));   // prints [72, 95, 58, 88]
    IO.println(scores);   // a type and hash, not the values!

    int[][] grid = new int[3][4];          // 3 rows, 4 columns
    grid[1][2] = 9;
    IO.println(Arrays.deepToString(grid));
    // prints [[0, 0, 0, 0], [0, 0, 9, 0], [0, 0, 0, 0]]

    int[] bigger = Arrays.copyOf(scores, 6);
    IO.println(Arrays.toString(bigger));
    // prints [72, 95, 58, 88, 0, 0]
}

What to learn

  • Declare, create and initialise arrays; default values (0, false, null)
  • Loop with an index and with for-each; length is a field, not a method
  • Two-dimensional arrays (arrays of arrays) for grids
  • Arrays.sort, toString, fill, copyOf, equals, binarySearch
  • Arrays are objects: assignment copies the reference, not the values

Free resources

Practice

Write a tic-tac-toe board as a char[3][3]: print it, place moves and write a method that returns the winner (checking rows, columns and both diagonals) or a draw.

Methods

A method is a named block of code with parameters and a return type (void if it returns nothing). Java always passes arguments by value: for objects, the value copied is the reference, so a method can change an object's contents but can't make the caller's variable point somewhere else.

You can overload a method (same name, different parameter types), take a variable number of arguments with ..., and call a method from itself (recursion). static methods belong to the class; instance methods (next topic) belong to an object.

static int area(int w, int h) { return w * h; }
static double area(double r) { return Math.PI * r * r; } // overload

static int sum(int... nums) {          // varargs
    int total = 0;
    for (int n : nums) total += n;
    return total;
}

static long factorial(int n) {        // recursion
    return n <= 1 ? 1 : n * factorial(n - 1);
}

static void tryToChange(int x, int[] arr) {
    x = 99;          // changes the local copy only
    arr[0] = 99;     // changes the shared array
}

void main() {
    IO.println(area(3, 4));                   // prints 12
    IO.println("%.2f".formatted(area(1.0)));  // prints 3.14
    IO.println(sum(1, 2, 3, 4));              // prints 10
    IO.println(factorial(20));     // prints 2432902008176640000
    int x = 1;
    int[] arr = {1};
    tryToChange(x, arr);
    IO.println(x + " " + arr[0]);             // prints 1 99
}

What to learn

  • Method signature: name, parameters, return type; return and void
  • Pass-by-value for primitives and references
  • Overloading and varargs
  • Recursion and the stack (and what a StackOverflowError means)
  • static vs instance methods
  • Small methods with clear names; one job per method

Free resources

Practice

Write a small math utility with methods isPrime, gcd (recursive), digitSum and max(int... values). Call each from main with a few test values and print the results.

Classes and objects

A class describes a kind of object: its fields (state) and methods (behaviour). A constructor sets up a new object; this refers to the current object. Keep fields private and expose behaviour through methods (encapsulation), so the class can check its own rules, like "a balance can't go below zero".

Objects live on the heap and are created with new. When nothing refers to an object any more, the garbage collector frees it; you never free memory by hand. Override toString() so your objects print usefully.

class Account {
    private final String owner;
    private long cents;                     // never negative
    private static int created = 0;         // shared by all accounts

    Account(String owner, long cents) {
        if (cents < 0) throw new IllegalArgumentException("negative");
        this.owner = owner;
        this.cents = cents;
        created++;
    }

    void withdraw(long amount) {
        if (amount > cents) throw new IllegalStateException("no funds");
        cents -= amount;
    }

    long balance() { return cents; }
    static int created() { return created; }

    @Override public String toString() {
        return owner + ": " + cents / 100 + "." + "%02d".formatted(cents % 100);
    }
}

void main() {
    var a = new Account("Ada", 10_050);
    a.withdraw(2_025);
    IO.println(a);                      // prints Ada: 80.25
    var b = a;                          // same object, two references
    b.withdraw(25);
    IO.println(a.balance());            // prints 8000
    IO.println(Account.created());      // prints 1
}

What to learn

  • Fields, methods and constructors; this and constructor chaining with this(...)
  • Access modifiers: private, package-private, protected, public
  • Encapsulation: private fields, methods that keep the object valid
  • static fields and methods vs instance members
  • References, null and NullPointerException
  • Object lifetime and garbage collection (no manual freeing)
  • Overriding toString(); initialiser order

Free resources

Practice

Model a library: Book (title, author, ISBN, available) and Library (a list of books with add, borrow, giveBack and findByAuthor). Make invalid states impossible: you can't borrow a book that's already out.

Packages, imports and the classpath

Real programs are many classes in many files. A package groups related classes and gives them a unique name, usually your reversed domain: com.example.shop.orders. The folder structure must match the package. import lets you use a class by its short name; everything in java.lang (String, Math…) is imported automatically.

The JVM finds classes on the classpath: a list of folders and .jar files. You'll rarely set it by hand, because build tools (stage 2) do it, but knowing what it is explains errors like ClassNotFoundException. Java 25 also lets you write import module java.base; to import every public package of a module at once.

# src/com/example/greet/Greeter.java   starts with: package com.example.greet;
# src/com/example/app/Main.java         starts with: package com.example.app;
#                                       import com.example.greet.Greeter;
javac -d out $(find src -name "*.java")    # compile into out/
java -cp out com.example.app.Main          # run with out/ on the classpath
jar --create --file app.jar --main-class com.example.app.Main -C out .
java -jar app.jar                          # run the packaged jar

What to learn

  • Package names, folder layout and the fully qualified class name
  • import, wildcard imports, static imports and name clashes
  • Package-private access: what "no modifier" means
  • The classpath, -cp, and ClassNotFoundException vs NoClassDefFoundError
  • Build and run a .jar with a main class

Free resources

Practice

Split your library program into two packages (model and app), compile it from the command line with javac -d, package it as a jar and run it with java -jar. Then make one class package-private and read the compiler error you get.

Exceptions and error handling

When something goes wrong, Java throws an exception, which travels up the call stack until a catch handles it (or the program stops and prints a stack trace). Checked exceptions (like IOException) must be caught or declared with throws; unchecked ones (RuntimeException subclasses such as IllegalArgumentException) don't have to be. Errors like OutOfMemoryError are not meant to be caught.

Use try-with-resources for anything that must be closed (files, connections): it closes them even when an exception is thrown. Catch exceptions where you can actually do something about them, never swallow them silently, and keep the original as the cause when you wrap one.

class InsufficientFundsException extends Exception {
    InsufficientFundsException(String msg) { super(msg); }
}

void pay(int balance, int amount) throws InsufficientFundsException {
    if (amount <= 0) throw new IllegalArgumentException("amount " + amount);
    if (amount > balance)
        throw new InsufficientFundsException("need " + (amount - balance));
}

void main() {
    try {
        pay(50, 80);
    } catch (InsufficientFundsException e) {
        IO.println("Declined: " + e.getMessage());  // prints Declined: need 30
    }

    try {
        Integer.parseInt("12a");
    } catch (NumberFormatException | NullPointerException e) {
        IO.println("bad input: " + e.getClass().getSimpleName());
        // prints bad input: NumberFormatException
    } finally {
        IO.println("always runs");            // prints always runs
    }

    try (var in = new java.io.StringReader("hi")) {  // closed automatically
        IO.println((char) in.read());         // prints h
    } catch (java.io.IOException e) {
        throw new java.io.UncheckedIOException(e);   // keep the cause
    }
}

What to learn

  • try / catch / finally, multi-catch and catch order
  • The hierarchy: Throwable → Error and Exception → RuntimeException
  • Checked vs unchecked exceptions and the throws clause
  • Try-with-resources and AutoCloseable
  • Writing your own exception classes; wrapping with a cause
  • Reading a stack trace: find the first line from your own code

Free resources

Practice

Write a calculator that reads lines like 12 / 4. Handle bad numbers, unknown operators and division by zero with clear messages and keep the loop running. Add one custom checked exception and decide where it should be caught.

Am I ready? Stage 1 quiz

What does System.out.println(7 / 2); print?

  1. 3.5
  2. 3
  3. 4
  4. It doesn't compile

Both operands are int, so Java does integer division and drops the remainder. Write 7 / 2.0 to get 3.5.

Two String variables hold the text "java". Which check reliably tells you the texts are the same?

  1. a == b
  2. a.hashCode() == b.hashCode()
  3. a.compareTo(b) > 0
  4. a.equals(b)

== compares references, which may differ for equal text. Equal hash codes don't prove equality either.

A method receives an int[] and sets arr[0] = 99. What does the caller see afterwards?

  1. arr[0] is 99, because the method got a copy of the reference to the same array
  2. The old value, because Java passes everything by value
  3. A compile error, because parameters are final
  4. It depends on whether the array is static

Java passes the reference by value. Both variables point at the same array, so changes to its contents are visible.

Which exception must be caught or declared with throws?

  1. NullPointerException
  2. IllegalArgumentException
  3. IOException
  4. ArithmeticException

IOException is a checked exception. The other three extend RuntimeException, so they are unchecked.

What is the main advantage of a switch expression with -> labels over the old switch statement?

  1. It runs faster
  2. No fall-through, it returns a value, and the compiler can check that every case is covered
  3. It works on double values
  4. It doesn't need a default for strings

Arrow labels never fall through, and a switch expression must be exhaustive, which catches forgotten cases at compile time.

Stage 2 · Intermediate Object-oriented Java and the standard library

Learn to design with interfaces, records, enums and sealed types, then master the tools every Java developer uses daily: generics, collections, lambdas and streams, dates, files, a build tool and unit tests. By the end of this stage you can build and test a real multi-class project with Maven or Gradle.

Inheritance, interfaces and polymorphism

A class can extend one other class and inherit its fields and methods, then override methods to change behaviour. An interface is a contract: a list of methods a class promises to provide. A class can implement many interfaces, and interfaces can carry default methods with a shared implementation.

Polymorphism means code written against a type (say, Shape) works with any subtype; the JVM calls the right override at run time. In practice, favour interfaces and composition (an object that has another object) over deep inheritance trees, which become fragile.

interface Shape {
    double area();
    default String describe() {
        return getClass().getSimpleName() + " " + "%.1f".formatted(area());
    }
}

abstract class Polygon implements Shape {
    abstract int sides();
}

class Square extends Polygon {
    private final double side;
    Square(double side) { this.side = side; }
    @Override public double area() { return side * side; }
    @Override int sides() { return 4; }
}

class Circle implements Shape {
    private final double r;
    Circle(double r) { this.r = r; }
    @Override public double area() { return Math.PI * r * r; }
}

void main() {
    List<Shape> shapes = List.of(new Square(3), new Circle(1));
    for (Shape s : shapes) IO.println(s.describe());
    // prints Square 9.0
    // prints Circle 3.1
    Shape s = shapes.get(0);
    if (s instanceof Polygon p) IO.println(p.sides() + " sides");
    // prints 4 sides
}

What to learn

  • extends, super, constructor chaining and method overriding with @Override
  • Abstract classes vs interfaces; default, static and private interface methods
  • Polymorphism and dynamic dispatch; upcasting and instanceof with a pattern variable
  • final classes and methods; why Object is the root of every class
  • Composition over inheritance; the Liskov substitution idea
  • Nested, inner, local and anonymous classes

Free resources

Practice

Model payment methods: an interface PaymentMethod with pay(amount), and implementations for card, bank transfer and wallet with different fees. Write a checkout that works with any of them, then add a fourth method without changing the checkout code.

Records, enums and object equality

A record is a compact, immutable data class: record Point(int x, int y) {} gives you a constructor, accessors, equals, hashCode and toString for free. Use records for values and DTOs; add a compact constructor to validate input.

An enum is a fixed set of named constants, and each constant is a full object that can have fields and methods. When you write a normal class whose objects go into a HashSet or HashMap, you must override equals and hashCode together (equal objects must have equal hash codes); records and enums already do this correctly.

record Money(long cents, String currency) {
    Money {                                   // compact constructor
        if (cents < 0) throw new IllegalArgumentException("negative");
        currency = currency.toUpperCase();
    }
    Money plus(Money other) {
        return new Money(cents + other.cents, currency);
    }
}

enum Planet {
    MERCURY(0.2408), EARTH(1.0), MARS(1.8808);
    final double orbitYears;
    Planet(double orbitYears) { this.orbitYears = orbitYears; }
}

void main() {
    var a = new Money(250, "eur");
    var b = new Money(250, "EUR");
    IO.println(a);                  // prints Money[cents=250, currency=EUR]
    IO.println(a.equals(b) + " " + (a == b));   // prints true false
    IO.println(a.plus(b).cents());       // prints 500
    IO.println(new HashSet<>(List.of(a, b)).size()); // prints 1

    for (Planet p : Planet.values())
        if (p.orbitYears > 1) IO.println(p + " " + p.ordinal());
    // prints MARS 2
    IO.println(Planet.valueOf("EARTH").orbitYears);  // prints 1.0
}

What to learn

  • Records: components, accessors, compact constructors, static factory methods
  • When a record fits (immutable data) and when it doesn't (JPA entities, mutable state)
  • Enums with fields, constructors and methods; values(), valueOf, EnumMap, EnumSet
  • The equals / hashCode contract and what breaks in a HashMap when you get it wrong
  • Comparable (natural order) vs Comparator (any order)
  • Immutability: final fields, defensive copies, why immutable objects are safe to share

Free resources

Practice

Write a Card record (rank and suit as enums), build a 52-card deck, shuffle it, deal two hands of five, and sort each hand by rank with a Comparator. Then write the same Card as a normal class without equals/hashCode and show that a HashSet now keeps duplicates.

Sealed types and pattern matching

A sealed interface or class lists exactly which types may implement it. Combined with records and pattern matching, this gives Java "algebraic data types": a switch over a sealed type can match each record, pull its fields out (record patterns), add conditions with when, and needs no default, because the compiler knows every case. Add a new subtype later and every switch that forgot it stops compiling.

This style is now the idiomatic way to model results, events, commands and syntax trees in modern Java. Use _ (the unnamed pattern) for parts you don't need.

sealed interface Shape permits Circle, Rect, Triangle {}
record Circle(double r) implements Shape {}
record Rect(double w, double h) implements Shape {}
record Triangle(double base, double height) implements Shape {}

double area(Shape s) {
    return switch (s) {               // no default: compiler checks all 3
        case Circle c -> Math.PI * c.r() * c.r();
        case Rect(double w, double h) -> w * h;
        case Triangle(var b, var h) -> b * h / 2;
    };
}

String size(Object o) {
    return switch (o) {
        case null -> "nothing";
        case Rect(var w, var h) when w == h -> "square " + w;
        case Rect(var w, _) -> "rect, width " + w;
        case String str when str.isBlank() -> "blank text";
        case Integer i -> "int " + i;
        default -> "other " + o.getClass().getSimpleName();
    };
}

void main() {
    IO.println(area(new Rect(2, 3)));        // prints 6.0
    IO.println(area(new Triangle(4, 5)));    // prints 10.0
    IO.println(size(new Rect(2, 2)));        // prints square 2.0
    IO.println(size(new Rect(2, 5)));        // prints rect, width 2.0
    IO.println(size(42));                    // prints int 42
    IO.println(size(null));                  // prints nothing
}

What to learn

  • sealed, permits, final and non-sealed subtypes
  • Pattern matching for instanceof and for switch
  • Record patterns, nested patterns, var in patterns and the unnamed pattern _
  • Guards with when, case null, and the dominance rules for case order
  • Exhaustiveness: why a switch over a sealed type needs no default
  • Modelling results and events as sealed records instead of flags and nulls

Free resources

Practice

Write a tiny expression calculator: a sealed interface Expr with records Num, Add, Mul and Neg. Write eval(Expr) and show(Expr) with switch expressions, then add Div and watch the compiler point at every switch you need to update.

Generics

Generics let a class or method work with any type while keeping type safety: a List<String> only accepts strings, and you never need a cast when you read from it. You'll use generic types constantly and write your own occasionally.

Bounded types (<T extends Comparable<T>>) restrict what T can be. Wildcards make APIs flexible; remember PECS: a producer you read from is ? extends T, a consumer you write into is ? super T. Generics are checked at compile time and erased at run time (type erasure), which is why you can't write new T().

record Pair<A, B>(A first, B second) {
    <C> Pair<A, C> withSecond(C value) { return new Pair<>(first, value); }
}

static <T extends Comparable<T>> T max(List<T> items) {
    T best = items.getFirst();
    for (T item : items) if (item.compareTo(best) > 0) best = item;
    return best;
}

static double sum(List<? extends Number> nums) {    // producer: extends
    double total = 0;
    for (Number n : nums) total += n.doubleValue();
    return total;
}

static void addOnes(List<? super Integer> target) { // consumer: super
    target.add(1);
    target.add(1);
}

void main() {
    var p = new Pair<>("age", 36);
    IO.println(p.withSecond(true));       // prints Pair[first=age, second=true]
    IO.println(max(List.of(3, 9, 4)));    // prints 9
    IO.println(max(List.of("pear", "apple")));  // prints pear
    IO.println(sum(List.of(1, 2.5, 3L)));       // prints 6.5
    List<Number> numbers = new ArrayList<>();
    addOnes(numbers);
    IO.println(numbers);                  // prints [1, 1]
}

What to learn

  • Using generic types: List<String>, Map<K, V> and the diamond <>
  • Writing generic classes, records and methods
  • Bounded type parameters and multiple bounds
  • Wildcards ?, ? extends T, ? super T and the PECS rule
  • Type erasure and its limits: no new T(), no instanceof List<String>, no primitive type arguments
  • Raw types and "unchecked" warnings in old code

Free resources

Practice

Write a generic Cache<K, V> with a maximum size that evicts the least recently used entry (hint: LinkedHashMap with access order), and a generic method static <T> List<List<T>> chunk(List<T> list, int size).

The Collections Framework

The collections in java.util are the data structures you'll use every day. List (ordered, duplicates allowed): ArrayList almost always. Set (no duplicates): HashSet, or TreeSet for sorted, LinkedHashSet for insertion order. Map (key → value): HashMap, TreeMap, LinkedHashMap. Queue/Deque: ArrayDeque for stacks and queues, PriorityQueue for "smallest first".

List.of, Set.of and Map.of create unmodifiable collections. Since Java 21, sequenced collections add getFirst(), getLast() and reversed() to lists, deques and ordered sets and maps. Know the big-O cost of the common operations, so you pick the right one.

void main() {
    var words = List.of("to", "be", "or", "not", "to", "be");

    Map<String, Integer> counts = new TreeMap<>();      // sorted keys
    for (String w : words) counts.merge(w, 1, Integer::sum);
    IO.println(counts);            // prints {be=2, not=1, or=1, to=2}

    SequencedSet<String> unique = new LinkedHashSet<>(words); // in order
    IO.println(unique + " " + unique.getFirst()); // prints [to, be, or, not] to

    List<String> sorted = new ArrayList<>(unique);
    sorted.sort(Comparator.comparing(String::length)
                          .thenComparing(Comparator.reverseOrder()));
    IO.println(sorted);            // prints [to, or, be, not]
    IO.println(sorted.reversed()); // prints [not, be, or, to]

    Deque<Integer> stack = new ArrayDeque<>();
    stack.push(1); stack.push(2); stack.push(3);
    IO.println(stack.pop() + " " + stack.peek());   // prints 3 2

    var pq = new PriorityQueue<>(List.of(5, 1, 4));
    IO.println(pq.poll());         // prints 1

    try {
        words.add("x");            // List.of is unmodifiable
    } catch (UnsupportedOperationException e) {
        IO.println("unmodifiable");  // prints unmodifiable
    }
}

What to learn

  • The interfaces: Collection, List, Set, Queue, Deque, Map, and the sequenced ones
  • The implementations and when to use each (ArrayList vs LinkedList, hash vs tree vs linked)
  • Big-O of get, add, contains and remove for each
  • Map helpers: getOrDefault, putIfAbsent, merge, computeIfAbsent
  • Sorting with Comparator.comparing, thenComparing, reversed
  • Unmodifiable (List.of, List.copyOf) vs mutable collections; ConcurrentModificationException
  • Iterating safely: Iterator.remove and removeIf

Free resources

Practice

Read a text file and print the ten most frequent words with their counts, ignoring case and punctuation. Then build an index: a Map<String, List<Integer>> from each word to the line numbers where it appears.

Lambdas and functional interfaces

A lambda is a short anonymous function: x -> x * 2. It can be used wherever a functional interface (an interface with one abstract method) is expected. java.util.function has the common ones: Function<T, R>, Predicate<T>, Consumer<T>, Supplier<T>, BiFunction, UnaryOperator and primitive versions such as IntPredicate.

Method references like String::length or System.out::println are shorthand for lambdas that just call a method. Lambdas can read local variables only if they are effectively final (never reassigned).

import java.util.function.*;

void main() {
    Function<Integer, Integer> doubleIt = x -> x * 2;
    Function<Integer, Integer> plusOne = x -> x + 1;
    IO.println(doubleIt.andThen(plusOne).apply(5));   // prints 11
    IO.println(doubleIt.compose(plusOne).apply(5));   // prints 12

    Predicate<String> isLong = s -> s.length() > 3;
    Predicate<String> startsJ = s -> s.startsWith("J");
    IO.println(isLong.and(startsJ).test("Java"));     // prints true
    IO.println(isLong.negate().test("Go"));           // prints true

    Supplier<List<String>> fresh = ArrayList::new;    // constructor ref
    List<String> names = fresh.get();
    names.addAll(List.of("bob", "alice", "eve"));
    names.removeIf(n -> n.length() == 3);
    names.replaceAll(String::toUpperCase);           // method ref
    names.forEach(IO::println);                       // prints ALICE

    int base = 10;                                    // effectively final
    IntBinaryOperator addBase = (a, b) -> a + b + base;
    IO.println(addBase.applyAsInt(1, 2));             // prints 13
}

What to learn

  • Lambda syntax: parameters, single expression vs block body
  • Functional interfaces and @FunctionalInterface
  • The core types in java.util.function and their primitive versions
  • Four kinds of method reference: static, bound, unbound, constructor
  • Composing with andThen, compose, and, or, negate
  • Effectively final captures; lambdas vs anonymous classes (this differs)

Free resources

Practice

Write a tiny validation library: a Validator<T> functional interface that returns a list of error messages, helpers like notBlank, minLength(n) and matches(regex), and an and method to combine them. Validate a sign-up form record with it.

Streams and Optional

The Stream API processes collections as a pipeline: a source, any number of lazy intermediate operations (filter, map, flatMap, sorted, distinct, limit) and one terminal operation (toList, collect, reduce, count, anyMatch) that runs it. Collectors.groupingBy, partitioningBy, joining and toMap do the classic reports in a few lines.

Optional is a return type that says "there may be no result", so callers handle the empty case instead of hitting a NullPointerException. Use it for return values, not fields or parameters. Streams are great for transforming data; a plain loop is still fine (and often clearer) for simple work or when you need early exits and checked exceptions.

import java.util.stream.*;

record Order(String customer, String product, int qty, double price) {
    double total() { return qty * price; }
}

void main() {
    var orders = List.of(
        new Order("ann", "pen", 10, 1.5), new Order("bob", "book", 1, 20),
        new Order("ann", "book", 2, 20), new Order("cy", "pen", 3, 1.5));

    List<String> bigBuyers = orders.stream()
        .filter(o -> o.total() >= 15)
        .map(Order::customer)
        .distinct()
        .sorted()
        .toList();
    IO.println(bigBuyers);                       // prints [ann, bob]

    Map<String, Double> revenue = orders.stream()
        .collect(Collectors.groupingBy(Order::product, TreeMap::new,
                 Collectors.summingDouble(Order::total)));
    IO.println(revenue);                    // prints {book=60.0, pen=19.5}

    IO.println(IntStream.rangeClosed(1, 5).map(i -> i * i).sum());
    // prints 55
    IO.println(Stream.of("a", "b", "c").collect(Collectors.joining("|")));
    // prints a|b|c

    Optional<Order> firstBig = orders.stream()
        .filter(o -> o.qty() > 50).findFirst();
    IO.println(firstBig.map(Order::customer).orElse("none"));
    // prints none
}

What to learn

  • Creating streams: from collections, Stream.of, IntStream.range, Files.lines
  • Intermediate vs terminal operations; laziness and short-circuiting
  • map, filter, flatMap, sorted, distinct, limit, reduce
  • Collectors: toList, toMap, groupingBy, partitioningBy, joining, counting
  • Primitive streams (IntStream…) and summaryStatistics
  • Optional: map, orElse, orElseThrow, ifPresent; never call get() blindly
  • When not to use streams; why parallel streams rarely help in web apps

Free resources

Practice

Load a CSV of sales (date, region, product, amount) and, with streams only, print: total per region, the best-selling product per month, the top 3 days, and the share of each region as a percentage. Then rewrite one of them as a loop and compare readability.

Dates and times

Use java.time and never the old Date and Calendar classes. Pick the type that matches what you mean: LocalDate (a calendar date, like a birthday), LocalDateTime (date and wall-clock time, no zone), ZonedDateTime (a time in a specific place), Instant (a point on the UTC timeline; store and log these). Duration measures time in seconds and nanoseconds; Period in years, months and days. All of them are immutable.

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

void main() {
    var release = LocalDate.of(2025, 9, 16);             // Java 25 GA
    IO.println(release.getDayOfWeek());                  // prints TUESDAY
    IO.println(release.plusMonths(6));                   // prints 2026-03-16
    IO.println(release.with(TemporalAdjusters.lastDayOfMonth()));
    // prints 2025-09-30
    IO.println(ChronoUnit.DAYS.between(release, LocalDate.of(2026, 9, 15)));
    // prints 364

    var meeting = ZonedDateTime.of(2026, 3, 29, 9, 0, 0, 0,
                                   ZoneId.of("Europe/London"));
    IO.println(meeting.withZoneSameInstant(ZoneId.of("Asia/Kolkata"))
                      .toLocalTime());                   // prints 13:30
    IO.println(meeting.toInstant());          // prints 2026-03-29T08:00:00Z

    var fmt = DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.UK);
    IO.println(release.format(fmt));                     // prints 16 Sept 2025
    IO.println(Duration.ofMinutes(135));                 // prints PT2H15M
    IO.println(Period.between(LocalDate.of(1990, 5, 20), release));
    // prints P35Y3M27D
}

What to learn

  • LocalDate, LocalTime, LocalDateTime, ZonedDateTime, OffsetDateTime, Instant
  • Duration vs Period; ChronoUnit.between
  • Time zones and daylight saving: why "add one day" and "add 24 hours" can differ
  • Formatting and parsing with DateTimeFormatter (and locales)
  • Store Instant/UTC, convert to a zone only for display
  • Clock for testable code; converting old Date values at the edges

Free resources

Practice

Build a meeting planner: given a meeting time in one city and a list of attendee cities, print each attendee's local time and flag anyone for whom it falls outside 08:00 to 18:00. Test it on a date when daylight saving changes in one city but not another.

Files and I/O

For files, use java.nio.file: a Path names a file and the Files class reads, writes, copies, moves, lists and walks them. Files.readString and Files.writeString cover small files in one line; Files.lines and BufferedReader stream big ones line by line. Always say which charset you mean (UTF-8 is the default since Java 18), and close streams with try-with-resources.

Underneath sit the classic java.io streams: InputStream/OutputStream for bytes and Reader/Writer for text. You'll meet them in network and library code. Avoid Java's built-in object serialization for anything new; it has a long history of security problems. Use JSON or another explicit format.

import java.nio.file.*;
import java.util.stream.Stream;

void main() throws Exception {
    Path dir = Files.createTempDirectory("demo");
    Path notes = dir.resolve("notes.txt");

    Files.writeString(notes, "one\ntwo\nthree\n");
    Files.writeString(notes, "four\n", StandardOpenOption.APPEND);
    List<String> lines = Files.readAllLines(notes);
    IO.println(lines.size() + " lines, last: " + lines.getLast());
    // prints 4 lines, last: four

    try (Stream<String> s = Files.lines(notes)) {    // lazy, for big files
        IO.println(s.filter(l -> l.contains("o")).count());   // prints 3
    }

    Files.copy(notes, dir.resolve("backup.txt"));
    try (Stream<Path> files = Files.list(dir)) {
        IO.println(files.map(p -> p.getFileName().toString())
                        .sorted().toList());  // prints [backup.txt, notes.txt]
    }
    IO.println(Files.size(notes) + " bytes");       // prints 19 bytes
    IO.println(dir.relativize(notes));              // prints notes.txt
}

What to learn

  • Path, Paths/Path.of, resolve, relativize, normalize
  • Files: read/write strings and lines, copy, move, delete, exists, walk, list
  • Streaming large files with Files.lines and BufferedReader
  • Byte vs character streams; charsets and UTF-8
  • Try-with-resources for every stream; UncheckedIOException
  • Reading from System.in and resources on the classpath (getResourceAsStream)
  • Why to avoid Java serialization; JSON instead

Free resources

Practice

Write a command-line tool dupes that walks a folder tree and lists files with identical content (group by size first, then compare SHA-256 hashes). Print the wasted space and make sure it doesn't crash on folders it can't read.

Build tools: Maven and Gradle

Real projects use a build tool to download dependencies, compile, run tests and package the app. Maven uses an XML pom.xml and a fixed lifecycle (compile → test → package → install); Gradle uses a Kotlin or Groovy build script and is more flexible and often faster. Both use the same project layout (src/main/java, src/test/java) and the same libraries from Maven Central. Learn one well; you'll be able to read the other.

Commit the wrapper (mvnw or gradlew) so everyone builds with the same tool version, set the Java release in the build file, and keep dependency versions in one place (a BOM or a version catalog).

<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>shop</artifactId>
  <version>1.0.0</version>

  <properties>
    <maven.compiler.release>25</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>            <!-- one version for all JUnit parts -->
        <groupId>org.junit</groupId>
        <artifactId>junit-bom</artifactId>
        <version>6.1.3</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <version>3.27.7</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>5.24.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.6.1</version>
      </plugin>
    </plugins>
  </build>
</project>
./mvnw test              # compile and run the unit tests
./mvnw package           # …and build target/shop-1.0.0.jar
./mvnw dependency:tree   # where did this library come from?
./gradlew build          # the Gradle equivalent of "mvn verify"

What to learn

  • The standard layout: src/main/java, src/main/resources, src/test/java
  • Maven coordinates (groupId, artifactId, version) and Maven Central
  • The Maven lifecycle and common goals; Gradle tasks (build, test, run)
  • Dependency scopes (compile, test, runtime, provided) and transitive dependencies
  • BOMs and version catalogs; reading dependency:tree to fix version conflicts
  • The Maven and Gradle wrappers; setting release 25 so the build is reproducible
  • Multi-module projects

Free resources

Practice

Turn your library program into a Maven project with the wrapper, add JUnit and one real library (for example Jackson), and run ./mvnw package. Then create the same project with Gradle (Kotlin DSL) and compare the two build files.

Unit testing with JUnit, AssertJ and Mockito

JUnit (now JUnit 6, which needs Java 17+) is the standard test framework. A test is a method annotated with @Test that arranges some data, acts, and asserts the result. @ParameterizedTest runs the same test over many inputs. AssertJ gives readable assertions (assertThat(list).containsExactly(...)), and Mockito replaces collaborators like a payment gateway with fakes you control.

Test behaviour, not implementation details; keep unit tests fast (no network or disk) so you run them constantly; and mock only what you don't own or what is slow. Integration tests with real databases come later with Testcontainers.

package com.example.shop;

public class PriceCalculator {
    public interface DiscountService { int percentFor(String customer); }

    private final DiscountService discounts;

    public PriceCalculator(DiscountService discounts) {
        this.discounts = discounts;
    }

    public long total(String customer, long cents, int qty) {
        if (qty <= 0) throw new IllegalArgumentException("qty must be > 0");
        long gross = cents * qty;
        return gross - gross * discounts.percentFor(customer) / 100;
    }
}
package com.example.shop;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class PriceCalculatorTest {
    PriceCalculator.DiscountService discounts =
        mock(PriceCalculator.DiscountService.class);
    PriceCalculator calc = new PriceCalculator(discounts);

    @Test
    void appliesTheCustomersDiscount() {
        when(discounts.percentFor("ann")).thenReturn(10);
        assertThat(calc.total("ann", 1_000, 3)).isEqualTo(2_700);
        verify(discounts).percentFor("ann");
    }

    @ParameterizedTest
    @CsvSource({"0, 500", "20, 400", "100, 0"})
    void handlesAnyDiscount(int percent, long expected) {
        when(discounts.percentFor(anyString())).thenReturn(percent);
        assertThat(calc.total("bob", 250, 2)).isEqualTo(expected);
    }

    @Test
    void rejectsZeroQuantity() {
        assertThatThrownBy(() -> calc.total("ann", 100, 0))
            .isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining("qty");
    }
}

What to learn

  • JUnit basics: @Test, @BeforeEach, @DisplayName, @Nested, assertThrows
  • Parameterized tests with @CsvSource, @ValueSource, @MethodSource
  • AssertJ fluent assertions for values, collections and exceptions
  • Mockito: mock, when … thenReturn, verify, argument matchers; when not to mock
  • Arrange / act / assert; one behaviour per test; good test names
  • Code coverage with JaCoCo, and why 100% isn't the goal
  • Test-driven development: write the failing test first

Free resources

Practice

Write tests first for a ShoppingCart (add, remove, quantities, a discount code, a total that can't go negative), then implement it until the tests pass. Mock the discount-code lookup. Run JaCoCo and add tests for any branch it shows as missed.

Am I ready? Stage 2 quiz

You override equals in a class but not hashCode. What goes wrong?

  1. The class no longer compiles
  2. toString stops working
  3. Equal objects can land in different HashMap/HashSet buckets, so lookups fail and duplicates appear
  4. Nothing, hashCode is only used for sorting

Equal objects must have equal hash codes. Records generate both for you, which is one reason to use them for values.

Why does a switch over a sealed interface not need a default branch?

  1. The compiler knows every permitted subtype, so it can check that all cases are covered
  2. Sealed types can't be null
  3. default is not allowed with records
  4. The JVM adds one automatically at run time

Exhaustiveness checking is the point: add a new subtype and every incomplete switch stops compiling.

Which method signature accepts a List<Integer> and a List<Double> and only reads numbers from them?

  1. sum(List<Number> nums)
  2. sum(List<? super Number> nums)
  3. sum(List<Object> nums)
  4. sum(List<? extends Number> nums)

Generics are invariant: List<Integer> is not a List<Number>. A producer you read from uses ? extends.

What happens when this runs? Stream.of(1, 2, 3).map(x -> { System.out.println(x); return x; });

  1. It prints 1, 2, 3
  2. Nothing is printed, because there is no terminal operation
  3. It prints 3, 2, 1
  4. It throws IllegalStateException

Intermediate operations are lazy. The pipeline only runs when a terminal operation such as toList() is called.

You need to store when an order was placed so users in any country see the right local time. Which type should you store?

  1. LocalDateTime
  2. LocalDate
  3. Instant (UTC), converted to a zone only for display
  4. A String like "05/11/2026 10:30"

LocalDateTime has no zone, so it can't say which moment it was. An Instant is one exact point in time.

Stage 3 · Advanced Concurrency, the JVM and working with data

Write code that does many things at once safely, from thread pools to virtual threads. Learn how the JVM runs, manages memory and collects garbage, how to measure performance, and how Java talks to databases and HTTP APIs. Finish with the habits that keep a codebase healthy and the changes that turn old Java into modern Java.

Concurrency: threads, executors and thread safety

A thread is an independent path of execution; all threads in a JVM share the same heap. When two threads change the same data without coordination you get race conditions: lost updates and values that are "impossible" according to the code. The Java Memory Model defines when one thread is guaranteed to see another's writes (the happens-before rule).

Don't create raw threads by hand; submit tasks to an ExecutorService. Protect shared state with, in order of preference: immutability (nothing to protect), thread confinement, ready-made concurrent classes (ConcurrentHashMap, AtomicLong, LongAdder), and finally synchronized or ReentrantLock. CompletableFuture chains asynchronous steps without blocking.

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

int unsafeCount = 0;                         // shared, unprotected
final AtomicInteger safeCount = new AtomicInteger();

void main() throws Exception {
    try (var pool = Executors.newFixedThreadPool(4)) {
        for (int t = 0; t < 4; t++) {
            pool.submit(() -> {
                for (int i = 0; i < 100_000; i++) {
                    unsafeCount++;           // read-modify-write race
                    safeCount.incrementAndGet();
                }
            });
        }
    }                                        // close() waits for tasks
    IO.println("atomic: " + safeCount.get());    // prints atomic: 400000
    IO.println("plain int lost updates: " + (unsafeCount < 400_000));
    // usually true: some increments were lost

    var words = new ConcurrentHashMap<String, Integer>();
    List.of("a", "b", "a").parallelStream()
        .forEach(w -> words.merge(w, 1, Integer::sum));
    IO.println(new TreeMap<>(words));         // prints {a=2, b=1}

    CompletableFuture<String> greeting = CompletableFuture
        .supplyAsync(() -> "order 42")
        .thenApply(s -> s + " shipped")
        .exceptionally(e -> "failed: " + e.getMessage());
    IO.println(greeting.get(1, TimeUnit.SECONDS)); // prints order 42 shipped
}

What to learn

  • Threads, Runnable, Callable, Future; thread states
  • Race conditions, visibility and the happens-before rule; volatile
  • ExecutorService and thread pools; shutting them down (close())
  • synchronized, ReentrantLock, ReadWriteLock; deadlocks and how to avoid them
  • Atomics, LongAdder, ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue
  • CountDownLatch, Semaphore and producer/consumer queues
  • CompletableFuture: supplyAsync, thenApply, thenCombine, allOf, error handling

Free resources

Practice

Write a parallel web-link checker: read 50 URLs, check them with a fixed pool of 8 threads, collect results in a thread-safe map and print a summary. Then introduce a deliberate race (a plain HashMap and an int counter), observe the wrong results, and fix it two different ways.

Virtual threads

Virtual threads (final since Java 21) are lightweight threads managed by the JVM instead of the operating system. You can run millions of them. When a virtual thread blocks on I/O (a database call, an HTTP request, a sleep), the JVM parks it and runs another one on the same OS thread. That means you can write simple, blocking, one-thread-per-request code and still handle huge numbers of concurrent requests, without reactive frameworks.

They help with I/O-bound work, not CPU-bound work. Don't pool them (create one per task) and limit access to scarce resources such as database connections with a Semaphore or the connection pool. Since Java 24, synchronized blocks no longer pin a virtual thread to its carrier, which removed the biggest early gotcha. In Spring Boot, one property turns them on for web requests.

import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

void main() {
    var done = new AtomicInteger();
    long start = System.nanoTime();

    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        for (int i = 0; i < 10_000; i++) {
            executor.submit(() -> {
                Thread.sleep(Duration.ofSeconds(1));  // pretend I/O wait
                done.incrementAndGet();
                return null;
            });
        }
    }   // waits for all 10,000 tasks

    long ms = (System.nanoTime() - start) / 1_000_000;
    IO.println(done.get() + " tasks done");        // prints 10000 tasks done
    IO.println("took about 1 s, not 10,000 s: " + (ms < 5_000));
    // prints took about 1 s, not 10,000 s: true

    Thread vt = Thread.ofVirtual().name("worker").start(() ->
        IO.println(Thread.currentThread().isVirtual()));  // prints true
    try { vt.join(); } catch (InterruptedException e) { }
}

What to learn

  • Platform threads vs virtual threads; carrier threads and mounting
  • Executors.newVirtualThreadPerTaskExecutor() and Thread.ofVirtual()
  • When they help (many blocking I/O calls) and when they don't (CPU-heavy work)
  • Don't pool virtual threads; limit scarce resources with semaphores or pools
  • Pinning: what it was, and what Java 24 fixed for synchronized
  • Turning them on in Spring Boot: spring.threads.virtual.enabled=true

Free resources

Practice

Write a program that makes 1,000 HTTP calls to a slow local endpoint (one that sleeps 200 ms). Time it with a fixed pool of 20 platform threads and with virtual threads. Then make the work CPU-bound (hash a large string 1,000 times per task) and see the difference disappear.

Structured concurrency and scoped values

Scoped values (final in Java 25) share an immutable value, such as the current user or request ID, with everything a thread calls, without passing it through every method. They are a safer, cheaper replacement for many uses of ThreadLocal, especially with millions of virtual threads.

Structured concurrency treats a group of subtasks as one unit: fork them inside a scope, join them, and if one fails the others are cancelled; nothing outlives the block. It is still a preview API in Java 25 to 27 (its shape changed between previews), so you need --enable-preview and should expect small changes. Learn the idea now; use it in production when it becomes final.

import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;

static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();

String loadUser()   { return "ann (" + REQUEST_ID.get() + ")"; }
int    loadOrders() { return 3; }

void main() throws Exception {
    ScopedValue.where(REQUEST_ID, "req-7").call(() -> {
        // Java 25 preview API: run with  java --enable-preview Structured.java
        try (var scope = StructuredTaskScope.open()) {
            Subtask<String> user = scope.fork(this::loadUser);
            Subtask<Integer> orders = scope.fork(this::loadOrders);
            scope.join();          // waits; throws if any subtask failed
            IO.println(user.get() + " has " + orders.get() + " orders");
            // prints ann (req-7) has 3 orders
        }
        return null;
    });
    IO.println(REQUEST_ID.isBound());           // prints false
}

What to learn

  • ScopedValue.where(…).run/call and how it differs from ThreadLocal
  • Why unstructured Futures leak work when one task fails
  • StructuredTaskScope: open, fork, join, joiners and cancellation
  • What "preview feature" means and how to enable one (--enable-preview)

Free resources

Practice

Write a "dashboard" endpoint that loads a user's profile, orders and recommendations in parallel with a structured task scope. Make the recommendations call throw and check that the other two subtasks are cancelled and the error reaches the caller.

How the JVM works

When you run java, the JVM loads classes on demand (through a hierarchy of class loaders), verifies their bytecode, then starts interpreting it. Methods that run often are compiled to fast machine code by the JIT compilers (C1 quickly, then C2 with heavy optimisation), which is why Java code gets faster after a warm-up.

Memory is split into the heap (all objects, shared by threads, managed by the garbage collector), a stack per thread (method frames and local variables) and metaspace (class metadata). Startup is the JVM's weak spot; recent releases attack it with class data sharing and Project Leyden's ahead-of-time cache (Java 24 to 26), which records loaded classes and method profiles from a training run.

javap -c -p Methods.class       # read the bytecode javac produced
java -Xlog:class+load -version | head   # watch classes being loaded
jcmd                            # list running JVMs and their PIDs
jcmd <pid> VM.flags             # flags in effect (heap size, GC…)
jcmd <pid> Thread.print         # thread dump: who is blocked on what
# Ahead-of-time cache (Java 25): train once, start faster afterwards
java -XX:AOTCacheOutput=app.aot -jar app.jar   # training run
java -XX:AOTCache=app.aot -jar app.jar         # later runs

What to learn

  • Class loading, linking and initialisation; the class loader hierarchy
  • Bytecode basics and reading javap -c output
  • Interpreter, C1/C2 JIT, tiered compilation and warm-up
  • Runtime memory areas: heap, stacks, metaspace, code cache
  • The JDK tools: jcmd, jstack, jps, jinfo
  • Startup improvements: CDS and the AOT cache (JEP 483, 514, 515)
  • GraalVM native images: instant startup, at the cost of build time and some dynamic features

Free resources

Practice

Compile a small class and read its bytecode with javap -c: find the loop, the method calls and string concatenation. Then take a thread dump of a running program with two threads deadlocked on two locks and point at the cycle in the output.

Memory and garbage collection

The garbage collector finds objects nothing can reach any more and frees their memory. Most objects die young, so collectors split the heap into generations and clean the young one often and cheaply. G1 is the balanced default (and since Java 27 the default everywhere); ZGC keeps pauses under a millisecond even on huge heaps; Parallel maximises throughput for batch jobs. Java 25 also made compact object headers a product option (on by default in Java 27), shrinking every object by 4 bytes.

Java can still leak memory: objects you no longer need but still reference (a growing static map, an unbounded cache, listeners never removed). Learn to read GC logs, set heap limits that fit your container, and take and analyse a heap dump when memory keeps growing.

java -Xms512m -Xmx512m -jar app.jar       # fixed heap size
java -XX:MaxRAMPercentage=75 -jar app.jar # in containers: % of the limit
java -XX:+UseZGC -jar app.jar             # sub-millisecond pauses
java -Xlog:gc:file=gc.log -jar app.jar    # GC log: pause times, heap after
jcmd <pid> GC.heap_info                   # heap usage right now
jcmd <pid> GC.heap_dump /tmp/heap.hprof   # open it in Eclipse MAT
java -XX:+HeapDumpOnOutOfMemoryError -jar app.jar   # dump on OOM

What to learn

  • Reachability, GC roots and why you never free memory yourself
  • Generational collection: young and old generations, minor and major collections
  • The collectors: G1 (default), ZGC, Parallel, Serial, Shenandoah, and when to pick each
  • Heap sizing: -Xmx, -Xms, MaxRAMPercentage in containers
  • Reading GC logs; pause time vs throughput
  • Memory leaks in Java and finding them with heap dumps (Eclipse MAT, VisualVM)
  • OutOfMemoryError kinds: heap space, metaspace, unable to create native thread

Free resources

Practice

Write a program that leaks: it adds a 1 KB array to a static list on every "request". Run it with -Xmx64m -XX:+HeapDumpOnOutOfMemoryError, open the dump in Eclipse MAT and find the list that holds everything. Then run a healthy version with G1 and with ZGC and compare the pause times in the GC logs.

Profiling and performance

Measure before you optimise. Java Flight Recorder (JFR) is built into the JDK and cheap enough to run in production: it records CPU samples, allocations, locks, GC and I/O. Open recordings in JDK Mission Control, or turn them into flame graphs with async-profiler.

For micro-benchmarks use JMH: naive timing loops lie, because the JIT removes dead code, warms up mid-measurement and inlines differently. Most real-world speed-ups come from fewer database round trips, better algorithms and less allocation, not from clever bytecode tricks.

# Record 60 seconds of a running app, then summarise it
java -XX:StartFlightRecording=duration=60s,filename=rec.jfr -jar app.jar
jfr summary rec.jfr                  # event counts
jfr view hot-methods rec.jfr         # where the CPU time goes
jfr view allocation-by-class rec.jfr # who allocates the most
jcmd <pid> JFR.start duration=30s filename=live.jfr   # on a live JVM

What to learn

  • JFR: starting a recording, jfr view, JDK Mission Control
  • CPU vs allocation vs lock profiling; flame graphs (async-profiler)
  • JMH benchmarks and the classic benchmarking mistakes
  • Common wins: right data structure, fewer allocations, batching I/O, caching
  • Latency percentiles (p50, p99) rather than averages

Free resources

Practice

Write a JMH benchmark comparing string concatenation in a loop, StringBuilder and String.join for 1,000 parts. Then record a JFR file of one of your own programs, find its hottest method with jfr view hot-methods and make it measurably faster.

Databases with JDBC

JDBC is Java's standard API for SQL databases; every framework, including JPA and Spring Data, uses it underneath. Get a Connection (in real apps from a connection pool such as HikariCP), run SQL through a PreparedStatement with ? placeholders, and read rows from a ResultSet. Placeholders aren't optional: building SQL by concatenating user input is how SQL injection happens.

Group statements that must succeed or fail together in a transaction (setAutoCommit(false), commit, rollback), and close everything with try-with-resources. The example uses the in-memory H2 database so it runs anywhere; the same code works with PostgreSQL by changing the URL and driver.

import java.sql.*;

void main() throws SQLException {
    String url = "jdbc:h2:mem:shop";     // PostgreSQL: jdbc:postgresql://…
    try (Connection db = DriverManager.getConnection(url, "sa", "")) {
        db.createStatement().execute("""
            CREATE TABLE product (id INT PRIMARY KEY,
                                  name VARCHAR(50), stock INT)""");

        String insert = "INSERT INTO product VALUES (?, ?, ?)";
        try (PreparedStatement ps = db.prepareStatement(insert)) {
            for (var p : List.of(List.of(1, "pen", 10), List.of(2, "ink", 0))) {
                ps.setInt(1, (Integer) p.get(0));
                ps.setString(2, (String) p.get(1));
                ps.setInt(3, (Integer) p.get(2));
                ps.addBatch();
            }
            ps.executeBatch();
        }

        db.setAutoCommit(false);             // start a transaction
        try (var ps = db.prepareStatement(
                "UPDATE product SET stock = stock - ? WHERE id = ?")) {
            ps.setInt(1, 3);
            ps.setInt(2, 1);
            ps.executeUpdate();
            db.commit();
        } catch (SQLException e) {
            db.rollback();
            throw e;
        }

        String userInput = "pen' OR '1'='1";  // an injection attempt
        try (var ps = db.prepareStatement(
                "SELECT name, stock FROM product WHERE name = ?")) {
            ps.setString(1, userInput);        // treated as plain text
            IO.println(ps.executeQuery().next());     // prints false
        }
        try (ResultSet rs = db.createStatement().executeQuery(
                "SELECT name, stock FROM product ORDER BY id")) {
            while (rs.next())
                IO.println(rs.getString("name") + " " + rs.getInt("stock"));
        }
        // prints pen 7
        // prints ink 0
    }
}

What to learn

  • Connection, PreparedStatement, ResultSet and JDBC URLs
  • Parameter placeholders and why string-built SQL is dangerous
  • Transactions: auto-commit, commit, rollback, isolation levels
  • Batch inserts and generated keys
  • Connection pools (HikariCP) and why opening a connection per query is slow
  • Schema migrations with Flyway or Liquibase
  • Mapping rows to records; when to reach for JPA or jOOQ instead

Free resources

Practice

Build a command-line to-do app on PostgreSQL (run it in Docker): a Flyway migration creates the table, a TodoRepository class does create/list/complete/delete with prepared statements, and "move all done items to the archive table" runs in one transaction that rolls back on error.

HTTP clients and JSON

The built-in java.net.http.HttpClient speaks HTTP/1.1 and HTTP/2 (and HTTP/3 since Java 26), synchronously or asynchronously, with timeouts and redirects. For JSON, Jackson is the standard library: it turns JSON into records and back. Jackson 3 (package tools.jackson) is what Spring Boot 4 uses; Jackson 2 (com.fasterxml.jackson) is still everywhere in older code.

Always set a timeout, check the status code before parsing the body, and treat every response from someone else's API as untrusted input. The example starts a tiny local server with the JDK's built-in HttpServer, so it runs offline.

import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import tools.jackson.databind.json.JsonMapper;

record Book(String title, int year) {}

void main() throws Exception {
    var mapper = JsonMapper.builder().build();

    // A tiny local API so the example runs offline
    var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
    server.createContext("/books/1", ex -> {
        byte[] body = mapper.writeValueAsBytes(new Book("Dune", 1965));
        ex.getResponseHeaders().add("Content-Type", "application/json");
        ex.sendResponseHeaders(200, body.length);
        ex.getResponseBody().write(body);
        ex.close();
    });
    server.start();

    var client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(5)).build();
    var request = HttpRequest.newBuilder(URI.create(
            "http://127.0.0.1:" + server.getAddress().getPort() + "/books/1"))
        .timeout(Duration.ofSeconds(5))
        .header("Accept", "application/json")
        .GET().build();

    HttpResponse<String> res =
        client.send(request, HttpResponse.BodyHandlers.ofString());
    IO.println(res.statusCode() + " " + res.body());
    // prints 200 {"title":"Dune","year":1965}
    if (res.statusCode() == 200) {
        Book book = mapper.readValue(res.body(), Book.class);
        IO.println(book.title() + " / " + book.year());  // prints Dune / 1965
    }
    server.stop(0);
}

What to learn

  • HttpClient, HttpRequest, HttpResponse and body handlers
  • Timeouts, redirects, headers, sendAsync with CompletableFuture
  • Status codes and error handling; retries with backoff for safe requests only
  • Jackson: JsonMapper, records, @JsonProperty, unknown fields, dates
  • Jackson 2 vs Jackson 3 package names (what changed in Spring Boot 4)
  • Reading an OpenAPI spec and calling an API from it

Free resources

Practice

Write a command-line weather or currency tool that calls a free public JSON API, maps the response to records with Jackson, handles timeouts and non-200 responses, and caches results for 10 minutes. Fetch five cities in parallel with sendAsync.

The module system (JPMS)

Since Java 9 the JDK itself is split into modules, and your code can be too. A module-info.java file says which modules yours requires and which packages it exports; everything else is hidden, even if it is public. That gives strong encapsulation and lets jlink build a small runtime with only the modules your app needs.

Most applications, including Spring Boot apps, still run on the classpath and don't declare modules, and that's fine. Know the basics because the JDK's encapsulation affects you anyway (reflection into JDK internals is blocked), libraries use them, and the OCP exam tests them.

// src/com.example.shop/module-info.java
module com.example.shop {
    requires java.net.http;              // a JDK module we use
    requires static org.jspecify;        // needed at compile time only
    exports com.example.shop.api;        // visible to other modules
    opens com.example.shop.dto to tools.jackson.databind; // reflection
}
// Build a trimmed runtime containing only the modules the app needs:
//   jlink --module-path out --add-modules com.example.shop --output rt

What to learn

  • module-info.java: requires, requires transitive, exports, opens, uses/provides
  • Module path vs classpath; named, automatic and unnamed modules
  • Strong encapsulation and --add-opens errors from old libraries
  • jdeps to see dependencies and jlink to build a custom runtime

Free resources

Practice

Turn a two-package command-line app into two modules (api and app), try to use a non-exported package from the other module and read the error, then build a runtime with jlink and compare its size with the full JDK.

Clean code, null safety and static analysis

Readable Java follows a few well-known habits: small classes with one job, names that explain intent, immutable objects by default, constructor injection, no null returns for "nothing found" (return an empty collection or Optional), and exceptions that say what went wrong. Effective Java by Joshua Bloch is the classic book on these idioms.

Let tools catch the rest: a formatter (google-java-format or Spotless) ends style debates, Error Prone and SpotBugs find real bugs at build time, and JSpecify annotations (@NullMarked, @Nullable, used across Spring 7) plus NullAway catch null pointer bugs before they run. Your IDE's inspections and a code review do the rest.

What to learn

  • Naming, small methods and classes, and the SOLID principles in practice
  • Immutability and constructor injection as defaults
  • Avoiding null: empty collections, Optional, Objects.requireNonNull
  • JSpecify @NullMarked / @Nullable and NullAway
  • Automatic formatting (Spotless) and static analysis (Error Prone, SpotBugs, PMD, Sonar)
  • Common design patterns: builder, factory, strategy, decorator, and when not to use them
  • Refactoring safely with tests and the IDE's refactoring tools

Free resources

Practice

Add Spotless, Error Prone and JSpecify (@NullMarked on your packages) to one of your earlier projects, fix everything they report, then refactor its longest method into smaller ones with tests passing after every step.

Modern Java: from Java 8 to 25

Lots of production code and online tutorials are still written in Java 8 or 11 style. Knowing what changed lets you read old code, upgrade it and avoid copying outdated patterns. The big steps: Java 8 (lambdas, streams, java.time), 11 (var, HttpClient, single-file launch), 17 (records, sealed classes, text blocks, switch expressions), 21 (virtual threads, pattern matching for switch, record patterns, sequenced collections) and 25 (compact source files, module imports, flexible constructor bodies, scoped values, the AOT cache).

Upgrade from one LTS to the next: update the build's release, run the tests, fix deprecation warnings and libraries that use JDK internals, then adopt new features gradually. OpenRewrite has recipes that automate much of it.

// Old style (Java 8): a mutable class, instanceof + cast, null checks
// class Point { private int x, y; getters, setters, equals, hashCode… }

// Java 25 style
record Point(int x, int y) {}
sealed interface Event permits Login, Purchase {}
record Login(String user) implements Event {}
record Purchase(String user, Point where, long cents) implements Event {}

String describe(Event e) {
    return switch (e) {
        case Login(var user) -> user + " logged in";
        case Purchase(var user, Point(var x, var y), var cents)
            when cents > 10_000 ->
                "big purchase by " + user + " at " + x + "," + y;
        case Purchase p -> p.user() + " spent " + p.cents() / 100.0;
    };
}

void main() {
    var events = List.of(new Login("ann"),
                         new Purchase("bob", new Point(3, 4), 25_000),
                         new Purchase("ann", new Point(0, 0), 1_250));
    events.stream().map(this::describe).forEach(IO::println);
    // prints ann logged in
    // prints big purchase by bob at 3,4
    // prints ann spent 12.5
    IO.println(events.getLast() instanceof Purchase(var u, _, _) ? u : "-");
    // prints ann
}

What to learn

  • The headline features of 8, 11, 17, 21 and 25 and how to recognise each era's code
  • Replacing getters/setters boilerplate with records, instanceof casts with patterns
  • The LTS upgrade path: build release, tests, deprecations, jdeps --jdk-internals
  • Automated upgrades with OpenRewrite recipes
  • Following new releases: JEPs, Inside Java, release notes

Free resources

Practice

Find an old Java 8 tutorial project on GitHub, upgrade it to Java 25 (build file first, then tests), and modernise three classes: one to a record, one instanceof chain to a pattern-matching switch, and one anonymous class to a lambda. Try an OpenRewrite migration recipe on a copy and compare.

Am I ready? Stage 3 quiz

Four threads each run count++ 100,000 times on a shared int. The result is often below 400,000. Why?

  1. The JIT skips some loop iterations
  2. count++ is a read-modify-write that isn't atomic, so concurrent updates get lost
  3. int overflows above 300,000
  4. Threads can't write to fields, only to local variables

Two threads can read the same value and both write value + 1. Use AtomicInteger, LongAdder or a lock.

When do virtual threads give the biggest improvement?

  1. CPU-heavy work like image resizing on an 8-core machine
  2. Code that never blocks
  3. When you reuse them in a small fixed pool
  4. Many concurrent tasks that spend most of their time waiting on I/O

A blocked virtual thread releases its carrier thread, so thousands of waiting tasks cost very little. CPU-bound work is still limited by the number of cores.

A service's memory grows until it fails with OutOfMemoryError: Java heap space, even though it uses a garbage collector. What is the most likely cause?

  1. Objects that are no longer needed are still referenced, for example from an unbounded static map or cache
  2. The GC is switched off by default
  3. The JIT compiler uses the heap for machine code
  4. Strings are never collected

The GC only frees unreachable objects. Take a heap dump and look for the collection that keeps growing.

Why should you use PreparedStatement with ? placeholders instead of building the SQL string from user input?

  1. It's the only way to run a SELECT
  2. It returns results in a different order
  3. Parameters are sent as data, never as SQL, which prevents SQL injection (and lets the database reuse the plan)
  4. It doesn't need a connection

With placeholders, input like ' OR '1'='1 is just a string value.

Your code uses a preview feature of Java 25. What does that mean?

  1. It's finished and safe to rely on in every future version
  2. It's complete but may still change or be removed; you must compile and run with --enable-preview
  3. It's only available in Oracle JDK
  4. It runs in a separate JVM

Preview features gather feedback before they become final. Structured concurrency is still a preview in Java 25 to 27.

Stage 4 · Professional Backend Java with Spring Boot

Build what most Java developers are paid to build: a production-ready REST API with Spring Boot 4, a PostgreSQL database, security, tests against real infrastructure, metrics and a container image. The examples in this stage fit together into one small "shop" API. Finish with a capstone project, and the OCP exam if you want a certificate.

Spring Boot basics and dependency injection

Spring is the most widely used Java framework, and Spring Boot is how almost everyone uses it: you pick starters (web, data, security…), Boot auto-configures sensible defaults, and the app runs as a single executable jar with an embedded web server. Spring Boot 4 (November 2025) is built on Spring Framework 7, needs Java 17 or newer, and uses Jakarta EE 11, Jackson 3 and JSpecify null-safety annotations.

The heart of Spring is dependency injection: you write classes that ask for what they need in their constructor, and Spring's application context creates them (as beans) and wires them together. That keeps classes small and easy to test. Configuration comes from application.yml, environment variables and profiles; bind your own settings to a record with @ConfigurationProperties.

# Generate a project (or use the web UI at start.spring.io)
DEPS=web,data-jpa,postgresql,flyway,validation,actuator,testcontainers
DEPS=$DEPS,security,oauth2-resource-server
curl https://start.spring.io/starter.zip -d type=maven-project \
  -d javaVersion=25 -d dependencies=$DEPS \
  -d groupId=com.example -d artifactId=shop -o shop.zip
unzip shop.zip -d shop && cd shop
./mvnw spring-boot:run      # starts on http://localhost:8080
package com.example.shop;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication              // component scan + auto-configuration
@ConfigurationPropertiesScan
public class ShopApplication {
    public static void main(String[] args) {
        SpringApplication.run(ShopApplication.class, args);
    }
}

@ConfigurationProperties("shop")    // binds shop.* from application.yml
record ShopProperties(int maxResults, String currency) {}
spring:
  application.name: shop
  datasource:
    url: jdbc:postgresql://localhost:5432/shop
    username: shop
    password: ${DB_PASSWORD}          # from the environment, never in git
  jpa:
    open-in-view: false
    hibernate.ddl-auto: validate      # Flyway owns the schema
  threads.virtual.enabled: true       # one virtual thread per request
  mvc.problemdetails.enabled: true    # RFC 9457 error bodies
  security.oauth2.resourceserver.jwt:
    jwk-set-uri: https://auth.example.com/.well-known/jwks.json
shop:
  max-results: 50
  currency: EUR
management.endpoints.web.exposure.include: health,info,metrics,prometheus

What to learn

  • Inversion of control: beans, the application context, component scanning
  • Constructor injection (and why field injection with @Autowired is discouraged)
  • @Component, @Service, @Repository, @Configuration and @Bean
  • Starters and auto-configuration; reading the conditions report (--debug)
  • application.yml, profiles, environment variables, @ConfigurationProperties records
  • Bean scopes and lifecycle; what a proxy is (it explains @Transactional surprises)
  • Spring Boot 4 changes: modular starters, Jackson 3, JSpecify, Java 17+ baseline

Free resources

Practice

Generate a project with Spring Initializr, add a GreetingService injected into a command-line runner, bind a greeting.* record with @ConfigurationProperties, and switch its message with a dev profile and with an environment variable. Run --debug and find one auto-configuration that was applied and one that wasn't.

REST APIs with Spring MVC

A @RestController maps HTTP requests to methods: @GetMapping, @PostMapping and friends, with @PathVariable, @RequestParam and @RequestBody for input. Return records (DTOs) rather than database entities, validate input with Bean Validation annotations and @Valid, and use the right status codes (201 with a Location header for a create, 404, 409…).

Handle errors in one place with @RestControllerAdvice and return Problem Details (RFC 9457), a standard JSON error format Spring supports out of the box. With virtual threads switched on, this ordinary blocking style scales to thousands of concurrent requests.

package com.example.shop;

import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import java.net.URI;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    public record CreateProduct(@NotBlank @Size(max = 100) String name,
                                @PositiveOrZero long priceCents,
                                @PositiveOrZero int stock) {}

    public record ProductDto(long id, String name, long priceCents, int stock) {
        static ProductDto from(Product p) {
            return new ProductDto(p.getId(), p.getName(),
                                  p.getPriceCents(), p.getStock());
        }
    }

    private final ProductService service;

    public ProductController(ProductService service) {   // injected
        this.service = service;
    }

    @GetMapping
    public List<ProductDto> search(@RequestParam(defaultValue = "") String q) {
        return service.search(q).stream().map(ProductDto::from).toList();
    }

    @GetMapping("/{id}")
    public ProductDto get(@PathVariable long id) {
        return ProductDto.from(service.get(id));
    }

    @PostMapping
    public ResponseEntity<ProductDto> create(
            @Valid @RequestBody CreateProduct body) {
        var p = service.create(body.name(), body.priceCents(), body.stock());
        return ResponseEntity.created(URI.create("/api/products/" + p.getId()))
                             .body(ProductDto.from(p));
    }
}
package com.example.shop;

import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

class ProductNotFoundException extends RuntimeException {
    ProductNotFoundException(long id) { super("No product with id " + id); }
}

@RestControllerAdvice
class ApiErrors {
    @ExceptionHandler(ProductNotFoundException.class)
    ProblemDetail notFound(ProductNotFoundException e) {
        var problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.NOT_FOUND, e.getMessage());
        problem.setTitle("Product not found");
        return problem;   // {"title":…,"status":404,"detail":…}
    }

    @ExceptionHandler(OutOfStockException.class)
    ProblemDetail outOfStock(OutOfStockException e) {
        return ProblemDetail.forStatusAndDetail(
            HttpStatus.CONFLICT, e.getMessage());
    }
}

What to learn

  • @RestController, request mappings, path variables, query parameters, request bodies
  • DTO records vs entities; mapping between them
  • Bean Validation: @NotBlank, @Size, @Email, @Valid, custom constraints
  • Status codes and ResponseEntity; 201 + Location, 204, 404, 409, 422
  • Global error handling with @RestControllerAdvice and ProblemDetail
  • Pagination and sorting (Pageable), API versioning, OpenAPI docs with springdoc
  • Calling other services with RestClient and HTTP interface clients

Free resources

Practice

Build the products API from these examples, add PUT and DELETE, pagination with Pageable, and an OpenAPI page with springdoc. Call every endpoint with the API tester, including invalid input, and check that every error comes back as a Problem Details body.

Data access: JPA, Hibernate and Spring Data

JPA (Jakarta Persistence) maps classes to tables; Hibernate is the implementation Spring Boot uses. An @Entity is loaded and tracked by the persistence context: change a field inside a transaction and Hibernate writes the UPDATE at commit (dirty checking). Spring Data JPA generates repository implementations from an interface, including queries derived from method names.

Own your schema with Flyway migrations rather than letting Hibernate create tables. Put @Transactional on service methods, not controllers. Learn to spot the N+1 query problem (one query for a list plus one per row for a lazy relation) and fix it with fetch joins or entity graphs; log the SQL while you develop so you see what JPA really does.

-- src/main/resources/db/migration/V1__create_product.sql
CREATE TABLE product (
    id          BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name        VARCHAR(100) NOT NULL,
    price_cents BIGINT NOT NULL CHECK (price_cents >= 0),
    stock       INT    NOT NULL CHECK (stock >= 0)
);
package com.example.shop;

import jakarta.persistence.*;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private long priceCents;
    private int stock;

    protected Product() {}                 // for JPA

    public Product(String name, long priceCents, int stock) {
        this.name = name;
        this.priceCents = priceCents;
        this.stock = stock;
    }

    public void removeStock(int qty) {     // rules live in the entity
        if (qty > stock) throw new OutOfStockException(name, stock);
        stock -= qty;
    }

    public Long getId() { return id; }
    public String getName() { return name; }
    public long getPriceCents() { return priceCents; }
    public int getStock() { return stock; }
}

class OutOfStockException extends RuntimeException {
    OutOfStockException(String name, int left) {
        super("Only " + left + " x " + name + " left");
    }
}
package com.example.shop;

import java.util.List;
import org.springframework.data.domain.Limit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface ProductRepository extends JpaRepository<Product, Long> {
    // SQL generated from the method name
    List<Product> findByNameContainingIgnoreCaseOrderByName(String text,
                                                          Limit limit);

    @Query("select p from Product p where p.stock < :min order by p.stock")
    List<Product> lowStock(int min);
}
package com.example.shop;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Limit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ProductService {
    private static final Logger log =
        LoggerFactory.getLogger(ProductService.class);
    private final ProductRepository repo;
    private final ShopProperties props;

    public ProductService(ProductRepository repo, ShopProperties props) {
        this.repo = repo;
        this.props = props;
    }

    @Transactional(readOnly = true)
    public List<Product> search(String text) {
        return repo.findByNameContainingIgnoreCaseOrderByName(
            text, Limit.of(props.maxResults()));
    }

    @Transactional(readOnly = true)
    public Product get(long id) {
        return repo.findById(id)
                   .orElseThrow(() -> new ProductNotFoundException(id));
    }

    @Transactional
    public Product create(String name, long priceCents, int stock) {
        return repo.save(new Product(name, priceCents, stock));
    }

    @Transactional                 // one transaction: all or nothing
    public void sell(long id, int qty) {
        Product p = get(id);
        p.removeStock(qty);        // no save(): dirty checking writes it
        log.info("Sold {} x {}", qty, p.getName());
    }
}

What to learn

  • Entities, ids and generation strategies, column mapping, embeddables
  • Relationships: @ManyToOne, @OneToMany, owning side, lazy vs eager loading
  • The persistence context, entity states and dirty checking
  • Spring Data repositories: derived queries, @Query, paging, projections
  • @Transactional: propagation, read-only, rollback rules, and the self-invocation trap
  • The N+1 problem, fetch joins, entity graphs; logging SQL
  • Flyway migrations; ddl-auto: validate; optimistic locking with @Version
  • Alternatives: Spring Data JDBC, JdbcClient, jOOQ

Free resources

Practice

Add Order and OrderLine entities with a Flyway migration. Write a "place order" service method that lowers stock for every line in one transaction and rolls back if any product is out of stock. Turn on SQL logging, list orders with their lines, spot the N+1 queries and fix them with a fetch join.

Security with Spring Security

Spring Security sits in front of your controllers as a chain of filters. It answers two questions: authentication (who is this?) and authorization (may they do this?). You configure it by declaring a SecurityFilterChain bean. Adding the starter locks everything down by default; you then open what should be public.

For an API used by a single-page app or mobile app, the usual setup is an OAuth 2.0 resource server: an identity provider (Keycloak, Auth0, Okta, Cognito…) issues signed JWT access tokens, and your API only checks the signature and the scopes. Server-rendered apps use sessions and form or OAuth login instead, and then must keep CSRF protection on. Store passwords only as slow hashes (bcrypt or Argon2) if you store them at all. The Authentication roadmap's Spring Security stage goes much deeper: login, resource servers, OIDC, method security, passkeys and MFA.

package com.example.shop;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {
    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
                .requestMatchers("/actuator/health").permitAll()
                .requestMatchers("/api/**").hasAuthority("SCOPE_products:write")
                .anyRequest().denyAll())
            // check the Bearer JWT's signature with the provider's keys
            .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()))
            .sessionManagement(s -> s.sessionCreationPolicy(
                SessionCreationPolicy.STATELESS))
            // no cookies or sessions: tokens come in a header, so no CSRF
            .csrf(csrf -> csrf.disable());
        return http.build();
    }
}

What to learn

  • The filter chain, SecurityFilterChain beans and the default lockdown
  • Authentication vs authorization; roles vs authorities vs scopes
  • URL rules with authorizeHttpRequests and method security (@PreAuthorize)
  • OAuth 2.0 and OpenID Connect: resource server (JWT) vs login (client)
  • Sessions, cookies and when CSRF protection is required
  • Password storage with PasswordEncoder (bcrypt/Argon2); CORS configuration
  • Common API risks: broken object-level authorization, mass assignment, leaking entities

Free resources

Practice

Run Keycloak in Docker, create a client and a products:write scope, and protect the shop API with it. Prove with the API tester that GET works without a token, POST fails with 401 without one and 403 with a token lacking the scope. Then add a rule that users can only see their own orders and test it with two users.

Testing Spring apps and Testcontainers

Test in layers. Plain unit tests cover services and domain logic with no Spring at all. Slice tests start only part of the app: @WebMvcTest loads controllers, advice and security with the service mocked (@MockitoBean), and @DataJpaTest loads only JPA. @SpringBootTest starts everything for a few end-to-end checks.

Test against the real database, not an in-memory stand-in: Testcontainers starts PostgreSQL (or Kafka, Redis…) in Docker for the test run, and Spring Boot's @ServiceConnection wires it in automatically. MockMvcTester gives AssertJ-style assertions for web tests.

package com.example.shop;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.assertj.MockMvcTester;

@WebMvcTest(ProductController.class)
@Import(SecurityConfig.class)
class ProductControllerTest {
    @Autowired MockMvcTester mvc;
    @MockitoBean ProductService service;

    static final String PEN = """
        {"name": "pen", "priceCents": 150, "stock": 5}""";

    @Test
    void unknownProductIsAProblemDetail() {
        when(service.get(99)).thenThrow(new ProductNotFoundException(99));
        assertThat(mvc.get().uri("/api/products/99"))
            .hasStatus(HttpStatus.NOT_FOUND)
            .bodyJson().extractingPath("$.title")
            .isEqualTo("Product not found");
    }

    @Test
    void creatingNeedsAToken() {
        assertThat(mvc.post().uri("/api/products")
                .contentType(MediaType.APPLICATION_JSON).content(PEN))
            .hasStatus(HttpStatus.UNAUTHORIZED);
    }

    @Test
    void createsWithTheRightScope() {
        var pen = new Product("pen", 150, 5);
        ReflectionTestUtils.setField(pen, "id", 7L);   // as if saved
        when(service.create("pen", 150, 5)).thenReturn(pen);
        assertThat(mvc.post().uri("/api/products")
                .with(jwt().authorities(
                    new SimpleGrantedAuthority("SCOPE_products:write")))
                .contentType(MediaType.APPLICATION_JSON).content(PEN))
            .hasStatus(HttpStatus.CREATED)
            .hasHeader("Location", "/api/products/7");
    }

    @Test
    void rejectsInvalidInput() {
        assertThat(mvc.post().uri("/api/products")
                .with(jwt().authorities(
                    new SimpleGrantedAuthority("SCOPE_products:write")))
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"name\": \"\", \"priceCents\": -1}"))
            .hasStatus(HttpStatus.BAD_REQUEST);
    }
}
package com.example.shop;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer;

@DataJpaTest                    // JPA + Flyway only, rolled back per test
@Testcontainers
class ProductRepositoryTest {
    @Container
    @ServiceConnection          // Boot points the DataSource at it
    static PostgreSQLContainer postgres =
        new PostgreSQLContainer("postgres:18");

    @Autowired ProductRepository repo;

    @Test
    void findsLowStockOnARealPostgres() {
        repo.save(new Product("pen", 150, 2));
        repo.save(new Product("ink", 900, 40));
        repo.save(new Product("pad", 300, 0));

        assertThat(repo.lowStock(5))
            .extracting(Product::getName)
            .containsExactly("pad", "pen");
    }
}

What to learn

  • The testing pyramid for a Spring app: unit, slice, full-context
  • @WebMvcTest with MockMvcTester and @MockitoBean
  • Testing security: jwt(), @WithMockUser, 401 vs 403
  • @DataJpaTest and @SpringBootTest; keeping the context cache warm
  • Testcontainers with @ServiceConnection; reusing containers locally
  • Running the app locally against containers (TestShopApplication)

Free resources

Practice

Cover the shop API: unit tests for Product.removeStock, a web slice test per endpoint including the 401/403/400/404/409 paths, a Testcontainers repository test, and one @SpringBootTest that places an order end to end. Make the whole suite run with ./mvnw verify in GitHub Actions.

Logging, metrics and observability

Log through SLF4J (Spring Boot uses Logback behind it) with placeholders (log.info("Sold {} x {}", qty, name)), at sensible levels, and in production as structured JSON logs, which Spring Boot supports with one property. Never log passwords, tokens or personal data.

Spring Boot Actuator adds health, info and metrics endpoints; Micrometer records metrics (request latency, JVM memory, your own counters) and exports them to Prometheus, and traces through OpenTelemetry, so you can follow one request across services. Expose only the endpoints you need, and keep them off the public internet.

package com.example.shop;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Component;

@Component
public class SalesMetrics {
    private final Counter itemsSold;

    public SalesMetrics(MeterRegistry registry) {
        this.itemsSold = Counter.builder("shop.items.sold")
            .description("Items sold since start-up")
            .register(registry);       // /actuator/prometheus shows
    }                                  // shop_items_sold_total

    public void recordSale(int qty) { itemsSold.increment(qty); }
}
# application.yml:  logging.structured.format.console: ecs   (JSON logs)
curl localhost:8080/actuator/health          # {"status":"UP"}
curl localhost:8080/actuator/metrics/jvm.memory.used
curl localhost:8080/actuator/prometheus | grep shop_items_sold

What to learn

  • SLF4J and Logback: levels, placeholders, per-package levels, MDC
  • Structured (JSON) logging and correlation ids
  • Actuator endpoints: health (liveness/readiness), info, metrics; securing them
  • Micrometer: counters, timers, gauges, tags; Prometheus and Grafana
  • Tracing with Micrometer Tracing / OpenTelemetry
  • What not to log: secrets, tokens, personal data

Free resources

Practice

Add JSON logging, a request-id in the MDC on every log line, and a shop.items.sold counter to the shop API. Run Prometheus and Grafana with Docker Compose, scrape the app, and build a dashboard with request rate, p99 latency, heap use and items sold.

Packaging and deploying Java apps

A Spring Boot app builds into one executable jar. To ship it, put it in a container image: either let Spring Boot build one with Cloud Native Buildpacks (./mvnw spring-boot:build-image, no Dockerfile needed) or write a multi-stage Dockerfile like the one below, which builds with the JDK and runs on a smaller JRE image as a non-root user.

Size the JVM for the container (MaxRAMPercentage), let the platform restart unhealthy instances using the Actuator health probes, and handle shutdown gracefully. For faster start-up, use the JDK's AOT cache (a training run at build time) or compile to a GraalVM native image for millisecond start-up and low memory, at the cost of long builds and some reflection limits.

# syntax=docker/dockerfile:1
FROM eclipse-temurin:25-jdk AS build
WORKDIR /src
COPY .mvn/ .mvn/
COPY mvnw pom.xml ./
RUN --mount=type=cache,target=/root/.m2 ./mvnw -B -q dependency:go-offline
COPY src/ src/
RUN --mount=type=cache,target=/root/.m2 ./mvnw -B -q package -DskipTests \
 && cp target/shop-*.jar app.jar \
 && java -Djarmode=tools -jar app.jar extract --destination out

FROM eclipse-temurin:25-jre
WORKDIR /app
COPY --from=build /src/out/ ./
USER 10001
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]
docker build -t shop:1.0 .
docker run --rm -p 127.0.0.1:8080:8080 -e DB_PASSWORD=… shop:1.0
./mvnw spring-boot:build-image   # or: buildpacks, no Dockerfile
./mvnw -Pnative native:compile   # GraalVM native executable

What to learn

  • Executable jars, the extracted layout and why it caches better in images
  • Multi-stage Dockerfiles with a JRE runtime image and a non-root user
  • Buildpacks (spring-boot:build-image) and Jib as Dockerfile-free options
  • JVM settings in containers: MaxRAMPercentage, GC choice, CPU limits
  • Health probes, graceful shutdown and twelve-factor configuration
  • Start-up options: CDS/AOT cache, GraalVM native image, and their trade-offs
  • CI/CD: build, test, scan and push the image on every merge

Free resources

Practice

Build the shop API image with the Dockerfile above and with spring-boot:build-image; compare size and start-up time. Run it with PostgreSQL in Docker Compose with health checks, then add an AOT cache training run and measure the start-up difference.

Beyond Spring: Quarkus, Micronaut, Jakarta EE and Kotlin

Spring is the default, but not the only choice. Quarkus and Micronaut do more work at build time for fast start-up and small memory use, and both are first-class with GraalVM native images. Jakarta EE (the successor of Java EE) is a set of standard APIs (Servlet, JPA, CDI, REST) implemented by servers such as WildFly, Payara and Open Liberty; Spring itself uses many of these APIs. Kotlin runs on the JVM, works with every Java library and is common on Android and increasingly on the backend.

Because they share the JDK, JPA, JUnit and Maven/Gradle, most of what you learned here carries over. Try one to understand the trade-offs; you don't need to master them.

What to learn

  • What Quarkus and Micronaut do differently (build-time DI, native-first)
  • Jakarta EE: the specifications and the application servers
  • Reactive programming (Project Reactor, WebFlux) and why virtual threads reduce the need for it
  • Kotlin on the JVM: null safety, data classes, coroutines, Java interop

Free resources

Practice

Rebuild the products endpoint in Quarkus (or Micronaut). Compare start-up time, memory use and the amount of code with the Spring version, in JVM mode and as a native executable.

OCP Java certification (1Z0-831)

Oracle's Oracle Certified Professional: Java SE 25 Developer exam (1Z0-831) is the current Java certification; the Java SE 21 version (1Z0-830) is also still offered. At the time of writing the Java 25 exam has 50 multiple-choice questions in 120 minutes with a 68% pass mark. It tests the language in fine detail: tricky compile errors, operator precedence, string and array behaviour, OOP rules, records, sealed classes, switch and patterns, exceptions, collections, streams, concurrency, I/O, modules and localisation.

Stages 1 to 3 cover the material; the exam rewards reading code precisely, so practise with timed mock questions and write small programs to settle every "does this compile?" doubt. It's optional: employers value a project you can show more, but the preparation makes you a much more precise Java developer. Check Oracle's exam page for the current topics, price and format before you book.

What to learn

  • Read the official exam topics and map each one to a topic on this roadmap
  • Tricky areas: initialisation order, overloading resolution, switch rules, generics, inheritance and access
  • Localisation: Locale, resource bundles, number and date formatting
  • Practise reading code without an IDE: predict output or the compile error
  • Take timed mock exams; review every wrong answer with a small program

Free resources

Practice

For every exam topic, write five "what does this print or why doesn't it compile?" snippets for yourself and check them with java Snippet.java. When you score 80% or more on two full timed mock exams in a row, book the exam.

Capstone: ship a production-ready Java service

Bring it all together in one project you can show employers: a small but real backend, built and run the way teams do it. Pick a domain you care about (a library, a booking system, a habit tracker, an inventory) and keep the scope small enough to finish.

What to learn

  • A Spring Boot 4 REST API on Java 25 with at least three related entities and Flyway migrations
  • Validation, Problem Details errors and an OpenAPI page
  • JWT security with at least two roles or scopes and an ownership rule
  • Unit, web slice and Testcontainers tests, run in CI on every push
  • Structured logs, Actuator health and a custom metric
  • A container image, a Docker Compose file to run it with PostgreSQL, and a README with one-command start
  • One feature that uses concurrency well (virtual threads calling an external API, a scheduled job, or async processing)

Free resources

Practice

Ship it: a public repository with a green CI badge, test coverage you can explain, a container image in a registry and the service running somewhere (a small cloud VM, a free tier, or your own machine). Ask a friend to clone it and start it with one command, and fix whatever they trip over.

Am I ready? Stage 4 quiz

Why is constructor injection preferred over @Autowired on fields?

  1. Field injection doesn't work in Spring Boot 4
  2. Constructors run faster
  3. Dependencies are explicit, fields can be final, and the class is easy to create in a plain unit test
  4. Spring can only proxy constructors

With constructor injection you can write new ProductService(fakeRepo, props) in a test, and an object can never exist half-wired.

A @Transactional method changes a field on an entity loaded from the repository but never calls save(). What happens at commit?

  1. Hibernate's dirty checking notices the change and writes an UPDATE
  2. Nothing: without save() changes are lost
  3. An exception, because the entity is detached
  4. The whole table is re-read

Entities loaded inside a transaction are managed; changes are flushed automatically when it commits.

Listing 100 orders runs 101 SQL queries. What is this, and what's a typical fix?

  1. A connection leak; increase the pool size
  2. Missing indexes; add one per column
  3. A transaction bug; remove @Transactional
  4. The N+1 problem from lazy relations; use a fetch join or entity graph

One query loads the orders, then each order's lazy collection triggers another query. A fetch join loads them together.

A request with a valid JWT that lacks the required scope hits a protected endpoint. What should the API return?

  1. 401 Unauthorized
  2. 403 Forbidden
  3. 404 Not Found
  4. 500 Internal Server Error

401 means "we don't know who you are"; 403 means "we know who you are, and you may not do this".

Why do the integration tests use Testcontainers with PostgreSQL instead of an in-memory H2 database?

  1. H2 can't run SQL
  2. Testcontainers is faster than H2
  3. Tests then run against the same database engine, SQL dialect and migrations as production
  4. Spring Boot 4 removed H2 support

An in-memory stand-in can pass tests that fail on the real database (types, constraints, SQL features). Testcontainers removes that gap.

How to use this roadmap

  • Type the examples yourself. Every Java example on this page is a complete program: save it under the file name in its first comment (or any name ending in .java) and run it with java File.java on JDK 25 or newer. Comments that say // prints … show the exact output; each one was checked by running the program. The Spring Boot examples in stage 4 fit together into one project, which was built and tested with Maven against PostgreSQL in November 2026.
  • Do the exercises. The 66 practice problems are free exercises on Exercism's Java track, which has an in-browser editor, automatic tests and optional free mentoring. Easy, medium and hard follow Exercism's own difficulty. Tick them off here as you solve them.
  • Use the filter. Core Java is the language, the standard library and the JVM: the base for any Java job, Android or data engineering. Spring backend adds what web backend jobs ask for. OCP Java SE 25 exam highlights the topics on Oracle's certification. The labels are a guide, not an official exam outline.
  • Which Java version? Learn on the latest LTS, Java 25 (September 2025). A new feature release ships every March and September (Java 26 in March 2026, Java 27 in September 2026) and the next LTS is Java 29 (September 2027). Many companies still run Java 17 or 21; everything in stages 1 to 3 works there too, except compact source files and IO.println (Java 25), so write the classic public static void main inside a class and use System.out.println on older versions.
  • Watch for outdated guides. If a tutorial uses Date or Calendar, anonymous classes where a lambda would do, getters and setters for plain data instead of records, javax.* imports in Spring code (now jakarta.*), WebSecurityConfigurerAdapter, @MockBean (now @MockitoBean) or JUnit 4's @RunWith, it predates modern Java and Spring. The ideas still apply; the code has moved on.
  • Track your progress. Ticking the first item in a topic marks it in progress; ticking them all marks it done. Progress stays in this browser. Use Export to move it to another device, or Share progress to send a link. Optional topics (dashed borders) don't count towards the percentage.
  • Related roadmaps: practise algorithms in Java with DSA, learn the database side with SQL & Databases, the language-independent server topics with Backend, package and run your services with Docker and Kubernetes, stream events with Apache Kafka, cache with Redis, secure them with Web Security and design bigger systems with System Design.

Java versions at a glance

Java 8 (2014, LTS)Lambdas, streams, Optional, java.time · topic
Java 11 (2018, LTS)var, HttpClient, java File.java, new String methods · topic
Java 17 (2021, LTS)Records, sealed classes, text blocks, switch expressions, pattern matching for instanceof · topic
Java 21 (2023, LTS)Virtual threads, pattern matching for switch, record patterns, sequenced collections · topic
Java 25 (2025, LTS)Compact source files and IO, module imports, flexible constructor bodies, scoped values, AOT cache ergonomics, compact object headers · topic
Java 26 (Mar 2026)HTTP/3 in HttpClient, AOT object caching with any GC, Applet API removed, warnings before "final means final"
Java 27 (Sep 2026)G1 the default GC everywhere, compact object headers on by default, post-quantum hybrid key exchange for TLS 1.3 · topic

Java cheat sheet

Run a filejava Hello.java · javac -d out Main.java + java -cp out Main · topic
Try codejshell · /vars, /methods, /exit
Recordrecord Point(int x, int y) {} · topic
Pattern switchswitch (shape) { case Circle c -> …; case Rect(var w, var h) -> …; } · topic
CollectionsList.of(…), new ArrayList<>(), map.merge(k, 1, Integer::sum) · topic
Streamslist.stream().filter(…).map(…).toList(), Collectors.groupingBy(…) · topic
Virtual threadstry (var ex = Executors.newVirtualThreadPerTaskExecutor()) { ex.submit(task); } · topic
FilesFiles.readString(Path.of("a.txt")), Files.lines(path) · topic
Maven / Gradle./mvnw verify, ./mvnw dependency:tree, ./gradlew build · topic
JVM toolsjcmd <pid> Thread.print, GC.heap_dump, JFR.start · topic
Spring Boot./mvnw spring-boot:run, ./mvnw spring-boot:build-image · topic

Format and inspect data with the JSON formatter and YAML ⇄ JSON converter (for application.yml), turn curl commands into Java HttpClient code with cURL to code, test your API with the API tester and decode tokens with the JWT decoder; all of them run in your browser and send nothing anywhere. Product and service names are examples, not endorsements. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates; Spring is a trademark of Broadcom Inc.; DevToolbox is not affiliated with either. Facts and links on this page were checked on 5 November 2026.