Free learning resource

Source code & resources

Every code example from Java Mastery: From First Program to JVM Internals — free to read, copy and run. No sign-up, no catch. If you found this from one of my courses, welcome; take the code and keep building.

Source code

Code from every lesson

31 examples, in lesson order.

1. Hello, Java: Your First Runnable Program Java

public class GameStart {
    public static void main(String[] args) {
        System.out.println("Welcome, brave hero.");
    }
}

2. Variables, Primitives, and Reference Types Java

public class Demo {
    public static void main(String[] args) {
        int heroLevel = 42;
        long totalXp = 9_500_000_000L;
        double critChance = 0.275;
        float spellPower = 88.5f;
        boolean isBossAlive = true;
        char heroRank = 'S';
        byte armorClass = 12;
        short manaPool = 30000;

        System.out.println("Level: " + heroLevel);
        System.out.println("XP: " + totalXp);
        System.out.println("Crit: " + critChance);
        System.out.println("Rank: " + heroRank);
    }
}

3. Operators and Expressions Java

public class Demo {
    public static void main(String[] args) {
        // Loot from a slain fire dragon
        int totalGold = 1000;
        int partySize = 3;

        // Integer slash integer truncates
        int goldEach = totalGold / partySize;
        int leftover = totalGold % partySize;

        // Damage uses plain multiplication
        int baseDamage = 25;
        int critMultiplier = 3;
        int finalBlow = baseDamage * critMultiplier;

        System.out.println("Gold each: " + goldEach);
        System.out.println("Leftover: " + leftover);
        System.out.println("Crit hit: " + finalBlow);
    }
}

4. Strings and Text Manipulation Java

public class Demo {
    public static void main(String[] args) {
        String reporter = "Vega";
        String original = reporter;
        reporter = reporter + " of the Tribune";
        System.out.println(original);
        System.out.println(reporter);
    }
}

5. Reading Input and Talking to the User Java

import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Hero name: ");
        String name = input.nextLine();
        System.out.println(
            "Welcome to the dungeon, "
            + name + "!");
        input.close();
    }
}

6. If, Else If, and Ternary Expressions Java

public class Demo {
    public static void main(String[] args) {
        int damage = 85;
        boolean isCritical = damage > 70;

        if (isCritical) {
            System.out.println("Critical hit!");
        }

        System.out.println("Dealt " + damage);
    }
}

7. Switch Statements and Switch Expressions Java

public class Demo {
  public static void main(String[] args) {
    String day = "SATURDAY";
    String type = "";
    switch (day) {
      case "SATURDAY":
      case "SUNDAY":
        type = "Raid Day";
        break;
      default:
        type = "Training Day";
        break;
    }
    System.out.println(day + ": " + type);
  }
}

8. For, While, and Do-While Loops Java

public class Demo {
    public static void main(String[] args) {
        System.out.println("Training mode on!");

        for (int rep = 1; rep <= 10; rep++) {
            int damage = rep * 12;
            System.out.println(
                "Strike " + rep
                + " dealt " + damage + " damage!"
            );
        }

        System.out.println("Training complete!");
    }
}

9. Break, Continue, and Labelled Loops Java

public class Demo {
  public static void main(String[] args) {
    int[] enemies = {12, 8, 25, 99, 14};
    int bossIndex = -1;
    for (int i = 0; i < enemies.length; i++) {
      if (enemies[i] >= 90) {
        bossIndex = i;
        break;
      }
    }
    System.out.println("Boss at index " + bossIndex);
  }
}

10. Arrays and Iteration Java

public class Demo {
    public static void main(String[] args) {
        int[] heroDamage = new int[4];

        heroDamage[0] = 25;
        heroDamage[1] = 40;
        heroDamage[2] = 15;
        heroDamage[3] = 88;

        System.out.println(
            "Slot 0 hits for " + heroDamage[0]);
        System.out.println(
            "Slot 3 hits for " + heroDamage[3]);
    }
}

11. Defining and Calling Methods Java

public class Demo {
    static void announceRival() {
        System.out.println("The Titans take the field!");
        System.out.println("Rank: 1");
    }

    public static void main(String[] args) {
        announceRival();
        System.out.println("Kickoff starts now!");
    }
}

12. Classes, Constructors, and Fields Java

class Spellbook {
    private String title;
    private int power;

    public Spellbook(String t, int p) {
        this.title = t;
        this.power = p;
    }
}

public class Demo {
    public static void main(String[] a) {
        Spellbook tome = new Spellbook(
            "Fireball Codex", 250);
        System.out.println("Tome created!");
    }
}

13. Inheritance and Polymorphism Visualized Java

public class Demo {
    static class Animal {
        String name;

        Animal(String name) {
            this.name = name;
        }

        void speak() {
            System.out.println(name + " makes a sound.");
        }
    }

    public static void main(String[] args) {
        Animal a = new Animal("Creature");
        a.speak();
    }
}

14. Interfaces and Abstract Classes in Practice Java

interface Drawable {
    void draw();
    void describe();
}

abstract class Shape
        implements Drawable {
    String name;
    Shape(String n) {
        this.name = n;
    }
    public void describe() {
        System.out.println(
            "Showing " + name);
    }
}

15. Records: Modern Data Carriers Java

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

    public static void main(String[] args) {
        Point spawn = new Point(3, 7);
        System.out.println(spawn);
    }
}

16. Lists, Sets, and Maps Java

import java.util.ArrayList;
import java.util.List;

public class SignInLog {
  public static void main(String[] args) {
    List<String> log = new ArrayList<>();
    log.add("alice");
    log.add("ravi");
    log.add("mei");
    log.add("alice");

    System.out.println("Sign-in log:");
    for (String user : log) {
      System.out.println(user);
    }
    System.out.println("Size: " + log.size());
  }
}

17. Generics: Type Safety Without Casts Java

import java.util.*;

public class Demo {
  public static void main(String[] args) {
    List shelf = new ArrayList();
    shelf.add("Atlas");
    shelf.add("Novel");
    shelf.add(999);

    for (Object item : shelf) {
      String s = (String) item;
      System.out.println("Got " + s);
    }
  }
}

18. Iterating with Iterator and For-Each Java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<String> plants = new ArrayList<>();
        plants.add("Basil");
        plants.add("Thyme");
        plants.add("Rosemary");

        Iterator<String> it = plants.iterator();
        while (it.hasNext()) {
            String plant = it.next();
            System.out.println("Watering " + plant);
        }
    }
}

19. Sorting and Comparing Objects Java

import java.util.*;

public class Demo {
    record Hero(String name, int level) {}

    public static void main(String[] a) {
        List<Hero> party = new ArrayList<>(
            List.of(
                new Hero("Cloud", 47),
                new Hero("Aerith", 38),
                new Hero("Tifa", 51),
                new Hero("Barret", 42)));

        party.sort(
            Comparator.comparingInt(Hero::level));

        for (Hero h : party) {
            System.out.println(
                h.name() + " lvl " + h.level());
        }
    }
}

20. Common Algorithms with the Collections API Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<String> loot = new ArrayList<>(
            List.of("Sword", "Potion",
                "Shield", "Gem"));

        Collections.shuffle(loot);

        System.out.println(
            "Random drop: " + loot);
    }
}

21. Threads, Runnables, and the Classic Model Java

public class Demo {
    public static void main(String[] args) {
        Runnable goblin = () -> {
            System.out.println(
                "Goblin spawned! Roar!");
        };
        Thread t = new Thread(goblin);
        t.start();
        System.out.println(
            "Main thread keeps moving.");
    }
}

22. ExecutorService and Thread Pools Java

import java.util.concurrent.*;

public class Demo {
    public static void main(String[] args)
            throws Exception {
        ExecutorService guild =
            Executors.newFixedThreadPool(3);
        Callable<String> quest = () -> {
            Thread.sleep(200);
            return "Goblin slain!";
        };
        Future<String> result =
            guild.submit(quest);
        System.out.println(result.get());
        guild.shutdown();
    }
}

23. CompletableFuture and Async Composition Java

import java.util.concurrent.CompletableFuture;
public class Demo {
    public static void main(String[] args) {
        CompletableFuture<String> quest =
            CompletableFuture.supplyAsync(() -> {
                return "Boss slain! 500 XP!";
            });
        System.out.println("Hero adventuring...");
        System.out.println(quest.join());
    }
}

24. Virtual Threads with Project Loom Java

public class Demo {
  public static void main(String[] args)
      throws InterruptedException {
    Thread hero = Thread.ofVirtual()
      .name("Link")
      .start(() -> {
        System.out.println(
          "Link wakes in Hyrule!");
      });
    hero.join();
    System.out.println(
      "The quest begins.");
  }
}

25. Parallel Streams and Fork/Join Java

import java.util.stream.LongStream;

public class Demo {
  public static void main(String[] args) {
    long start = System.nanoTime();
    long xp = LongStream
      .rangeClosed(1, 50_000_000)
      .sum();
    long ms = (System.nanoTime() - start)
      / 1_000_000;
    System.out.println(
      "Total XP grinded: " + xp);
    System.out.println(
      "Run took " + ms + " ms.");
  }
}

26. Lambdas and Functional Interfaces Java

public class Demo {
    public static void main(String[] args) {
        Runnable oldWay = new Runnable() {
            @Override
            public void run() {
                System.out.println("Boss alarm!");
            }
        };
        oldWay.run();
        System.out.println("Anonymous done.");
    }
}

27. Stream API: Map, Filter, Reduce Java

import java.util.List;

public class Demo {
  public static void main(String[] args) {
    List<Integer> levels = List.of(1, 2, 3);

    List<Integer> xp = levels.stream()
        .map(lvl -> lvl * 100)
        .toList();

    System.out.println("XP earned: " + xp);
  }
}

28. Collectors and Grouping Java

import java.util.*;
import java.util.stream.*;

public class Demo {
    record Hero(String name, String team) {}

    public static void main(String[] a) {
        var roster = List.of(
            new Hero("Thor", "Avengers"),
            new Hero("Hulk", "Avengers"),
            new Hero("Storm", "X-Men"),
            new Hero("Logan", "X-Men")
        );
        var byTeam = roster.stream()
            .collect(Collectors
                .groupingBy(Hero::team));
        byTeam.forEach((team, list) ->
            System.out.println(team
                + ": " + list.size()));
    }
}

29. Optional: Banishing Null Pointer Exceptions Java

import java.util.Optional;

public class Demo {
    public static void main(String[] args) {
        Optional<String> sword =
            Optional.of("Master Sword");

        Optional<String> empty =
            Optional.empty();

        String maybe = null;
        Optional<String> pet =
            Optional.ofNullable(maybe);

        System.out.println(sword);
        System.out.println(empty);
        System.out.println(pet);
    }
}

30. Try-With-Resources and Exception Idioms Java

import java.io.BufferedReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

public class Demo {
  public static void main(String[] args)
      throws IOException {
    Path scroll = Files.createTempFile(
        "quest", ".txt");
    Files.writeString(scroll,
        "Defeat the Frost Wyrm");
    try (BufferedReader br =
        Files.newBufferedReader(scroll)) {
      String line = br.readLine();
      System.out.println("Quest: " + line);
    }
  }
}

31. Pattern Matching, Sealed Classes, and Where Java Is Heading Java

public class Spellbook {

    sealed interface Spell permits
        Damage, Crit, Combo {}

    record Damage(int hit)
        implements Spell {}

    record Crit(Spell base, int m)
        implements Spell {}

    record Combo(Spell a, Spell b)
        implements Spell {}
}