Skip to content
Tutorials Center
My learning

Topics

Lesson 200 of 201 ยท Practice and Review

Java Practice Exercises

30 graded Java exercises with solutions on strings, loops, arrays, recursion, classes, records, exceptions, collections, streams and threads. Run them online.

You learn to program by programming. Reading lessons builds knowledge, but only solving problems on your own builds the skill of turning an idea into working code. This page has 30 exercises that cover the whole course, grouped by topic and graded from Beginner to Advanced. Each one has a short task, a live editor with starter code that already compiles, and a hidden solution.

To get the most out of them:

  • Try first, peek later. Give every exercise a real attempt before you open the solution. Being stuck for ten minutes is not wasted time: that's when you learn the most.
  • Run early and often. Every starter calls your code with test values and shows the expected output in comments, so you can compare as you go. The starters compile as given, with placeholder bodies such as return 0; that you replace.
  • Compare, don't copy. A different solution can be just as correct. Read ours for ideas, then improve your own version.

Every group links to the lesson it practices, and the cheat sheet is a handy companion. Exercises that read input have values preset in the Input box, which you can change to test other cases. If you'd like to study worked examples first, the 40 classic programs are a good warm-up.

Basics and formatting

These practice variables, printing output, reading input, arithmetic operators and formatting strings.

1. Receipt line (Beginner)

Read an item name, a unit price and a quantity, one per line, and print a receipt line with the price and total formatted to two decimals.

Java Exercise 1: Receipt line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
void main() {
    String item = IO.readln();
    double price = Double.parseDouble(IO.readln().trim());
    int quantity = Integer.parseInt(IO.readln().trim());

    System.out.printf("%d x %s @ %.2f = %.2f%n", quantity, item, price, price * quantity);
}

IO.readln() always returns text, so the numbers need Double.parseDouble and Integer.parseInt; %.2f rounds to two decimals and %n ends the line.

2. Seconds to clock time (Beginner)

Write formatDuration(int totalSeconds) that returns the time as h:mm:ss, with minutes and seconds always two digits.

Java Exercise 2: Clock time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
String formatDuration(int totalSeconds) {
    int hours = totalSeconds / 3600;
    int minutes = totalSeconds % 3600 / 60;
    int seconds = totalSeconds % 60;
    return "%d:%02d:%02d".formatted(hours, minutes, seconds);
}

Integer division gives whole hours, % gives what's left over, and the %02d specifier pads with a leading zero.

3. Making change (Beginner)

Write makeChange(int cents) that breaks an amount into the fewest coins from 200, 100, 50, 20, 10, 5, 2 and 1 cents, returned as text like 2x20 (count x coin, separated by spaces, largest coin first).

Java Exercise 3: Making change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
String makeChange(int cents) {
    int[] coins = {200, 100, 50, 20, 10, 5, 2, 1};
    StringJoiner result = new StringJoiner(" ");
    for (int coin : coins) {
        int count = cents / coin;
        if (count > 0) {
            result.add(count + "x" + coin);
            cents %= coin;
        }
    }
    return result.toString();
}

Taking as many of the largest coin as possible (the greedy method) is optimal for this coin set. StringJoiner adds the separators only between items.

Strings

These practice Strings, String Methods, StringBuilder and Characters and Booleans.

4. Initials (Beginner)

Write initials(String fullName) that returns the uppercase initials followed by dots. Extra spaces anywhere must not matter.

Java Exercise 4: Initials

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
String initials(String fullName) {
    StringBuilder result = new StringBuilder();
    for (String part : fullName.strip().split("\\s+")) {
        result.append(Character.toUpperCase(part.charAt(0))).append('.');
    }
    return result.toString();
}

Stripping first and splitting on the regex \\s+ (one or more whitespace characters) means no empty parts, so charAt(0) is always safe.

5. Caesar cipher (Intermediate)

Write caesar(String text, int shift) that shifts every letter by shift places in the alphabet, wrapping around from z to a and keeping upper and lower case. Other characters stay as they are, and negative shifts decode.

Java Exercise 5: Caesar cipher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
String caesar(String text, int shift) {
    StringBuilder out = new StringBuilder(text.length());
    for (char c : text.toCharArray()) {
        if (c >= 'a' && c <= 'z') {
            out.append((char) ('a' + Math.floorMod(c - 'a' + shift, 26)));
        } else if (c >= 'A' && c <= 'Z') {
            out.append((char) ('A' + Math.floorMod(c - 'A' + shift, 26)));
        } else {
            out.append(c);
        }
    }
    return out.toString();
}

Math.floorMod always returns a value from 0 to 25, even for negative shifts, where the % operator would give a negative remainder.

6. Missing letters (Intermediate)

Write missingLetters(String text) that returns, in alphabetical order, every English letter that does not appear in the text, ignoring case. A pangram returns an empty string.

Java Exercise 6: Missing letters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
String missingLetters(String text) {
    boolean[] seen = new boolean[26];
    for (char c : text.toLowerCase().toCharArray()) {
        if (c >= 'a' && c <= 'z') seen[c - 'a'] = true;
    }
    StringBuilder missing = new StringBuilder();
    for (int i = 0; i < 26; i++) {
        if (!seen[i]) missing.append((char) ('a' + i));
    }
    return missing.toString();
}

One boolean slot per letter records what was seen; c - 'a' turns a letter into its index and (char) ('a' + i) turns it back.

Control flow and loops

These practice if and else, switch, while loops, for loops and break and continue.

7. FizzBuzz (Beginner)

Write label(int n): "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for multiples of both, and the number itself otherwise.

Java Exercise 7: FizzBuzz

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
String label(int n) {
    if (n % 15 == 0) return "FizzBuzz";
    if (n % 3 == 0) return "Fizz";
    if (n % 5 == 0) return "Buzz";
    return String.valueOf(n);
}

The "both" case must be tested first; otherwise 15 would stop at the % 3 check and print just Fizz.

8. Letter grades with switch (Beginner)

Write letterGrade(int score) for scores from 0 to 100 using a switch expression on score / 10: 90 and above is A, 80s B, 70s C, 60s D, below 60 F. Throw IllegalArgumentException for scores outside 0 to 100.

Java Exercise 8: Letter grades

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
char letterGrade(int score) {
    if (score < 0 || score > 100) {
        throw new IllegalArgumentException("score out of range: " + score);
    }
    return switch (score / 10) {
        case 10, 9 -> 'A';
        case 8 -> 'B';
        case 7 -> 'C';
        case 6 -> 'D';
        default -> 'F';
    };
}

Integer division maps 90 to 99 onto 9, and one case label can list several values. The validation runs first, so default only ever sees 0 to 5.

9. Collatz steps (Intermediate)

The Collatz rule: if n is even, halve it; if it's odd, replace it with 3n + 1. Write collatzSteps(long n) that counts the steps needed to reach 1. Then find the starting number below 1000 that needs the most steps.

Java Exercise 9: Collatz steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
int collatzSteps(long n) {
    int steps = 0;
    while (n != 1) {
        n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
        steps++;
    }
    return steps;
}

// in main:
int bestStart = 1, bestSteps = 0;
for (int start = 1; start < 1000; start++) {
    int steps = collatzSteps(start);
    if (steps > bestSteps) {
        bestStart = start;
        bestSteps = steps;
    }
}
IO.println(bestStart + " needs " + bestSteps + " steps");

The parameter is a long because the sequence climbs far above its starting value before it falls; for larger starts (113,383 is the first) an int would overflow.

10. Guessing game judge (Intermediate)

The secret number is 37. Read guesses from the Input box one line at a time and answer Too low or Too high. When a guess is right, print how many guesses it took and stop, even if more input is left. If the input runs out first, print Out of guesses.

Java Exercise 10: Guessing game

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
void main() {
    int secret = 37;
    Scanner in = new Scanner(System.in);
    int guesses = 0;

    while (in.hasNextInt()) {
        int guess = in.nextInt();
        guesses++;
        if (guess == secret) {
            IO.println(guess + ": Correct in " + guesses + " guesses!");
            return;
        }
        IO.println(guess + (guess < secret ? ": Too low" : ": Too high"));
    }
    IO.println("Out of guesses");
}

hasNextInt() ends the loop cleanly when input runs out, and return leaves main the moment the guess is right, so the last line only runs when every guess was wrong.

Arrays

These practice Arrays, Looping Through Arrays, Multidimensional Arrays and The Arrays Class.

11. Running totals (Beginner)

Write runningTotals(int[] values) that returns a new array where each element is the sum of all values up to and including that position. Don't change the input array.

Java Exercise 11: Running totals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
int[] runningTotals(int[] values) {
    int[] totals = new int[values.length];
    int sum = 0;
    for (int i = 0; i < values.length; i++) {
        sum += values[i];
        totals[i] = sum;
    }
    return totals;
}

A separate result array keeps the input untouched, and a single running sum makes it O(n) instead of re-adding from the start each time.

12. Deduplicate a sorted array in place (Intermediate)

Given a sorted array, move the distinct values to the front, in order, without creating another array, and return how many there are.

Java Exercise 12: Deduplicate in place

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
int dedupe(int[] sorted) {
    if (sorted.length == 0) return 0;
    int write = 1;
    for (int read = 1; read < sorted.length; read++) {
        if (sorted[read] != sorted[write - 1]) {
            sorted[write++] = sorted[read];
        }
    }
    return write;
}

Two indexes do the work: read visits every element, and write marks where the next new value goes. Because the array is sorted, a value is new exactly when it differs from the last one kept.

13. Diagonal sums (Beginner)

Write diagonalSums(int[][] square) that returns a two-element array: the sum of the main diagonal (top-left to bottom-right) and of the anti-diagonal (top-right to bottom-left).

Java Exercise 13: Diagonal sums

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
int[] diagonalSums(int[][] square) {
    int n = square.length, main = 0, anti = 0;
    for (int i = 0; i < n; i++) {
        main += square[i][i];
        anti += square[i][n - 1 - i];
    }
    return new int[] {main, anti};
}

On the main diagonal the row and column indexes are equal; on the anti-diagonal they always add up to n - 1. One loop covers both.

14. Spiral order (Advanced)

Write spiral(int[][] matrix) that returns all values in clockwise spiral order, starting at the top-left corner. It must work for rectangular matrices too.

Java Exercise 14: Spiral order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
List<Integer> spiral(int[][] matrix) {
    List<Integer> result = new ArrayList<>();
    int top = 0, bottom = matrix.length - 1;
    int left = 0, right = matrix[0].length - 1;

    while (top <= bottom && left <= right) {
        for (int c = left; c <= right; c++) result.add(matrix[top][c]);
        top++;
        for (int r = top; r <= bottom; r++) result.add(matrix[r][right]);
        right--;
        if (top <= bottom) {
            for (int c = right; c >= left; c--) result.add(matrix[bottom][c]);
            bottom--;
        }
        if (left <= right) {
            for (int r = bottom; r >= top; r--) result.add(matrix[r][left]);
            left++;
        }
    }
    return result;
}

Four boundaries shrink after each side is walked. The two if checks stop the last row or column from being visited twice in non-square matrices.

Methods and recursion

These practice Methods, Parameters and Return Values, Varargs and Recursion.

15. Fast power (Intermediate)

Write a recursive power(long base, int exponent) for non-negative exponents that uses "exponentiation by squaring": x^n = (x^(n/2))ยฒ for even n, and x ยท x^(nโˆ’1) for odd n. It needs only about logโ‚‚ n multiplications.

Java Exercise 15: Fast power

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
long power(long base, int exponent) {
    if (exponent == 0) return 1;
    if (exponent % 2 == 0) {
        long half = power(base, exponent / 2);
        return half * half;
    }
    return base * power(base, exponent - 1);
}

Computing half once and squaring it is the whole trick: calling power(base, exponent / 2) twice would bring back the slow linear version.

16. Average with varargs (Beginner)

Write average(double... values) that returns an OptionalDouble: empty when no values are given, otherwise the mean.

Java Exercise 16: Varargs average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
OptionalDouble average(double... values) {
    if (values.length == 0) return OptionalDouble.empty();
    double sum = 0;
    for (double v : values) sum += v;
    return OptionalDouble.of(sum / values.length);
}

Inside the method values is an ordinary double[], empty when the caller passes nothing. Arrays.stream(values).average() returns exactly the same result in one line.

17. All permutations (Advanced)

Write permutations(String text) that returns every ordering of the characters, in the order produced by trying each remaining character first. Assume the characters are distinct.

Java Exercise 17: Permutations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
List<String> permutations(String text) {
    List<String> result = new ArrayList<>();
    permute("", text, result);
    return result;
}

void permute(String prefix, String remaining, List<String> result) {
    if (remaining.isEmpty()) {
        result.add(prefix);
        return;
    }
    for (int i = 0; i < remaining.length(); i++) {
        String rest = remaining.substring(0, i) + remaining.substring(i + 1);
        permute(prefix + remaining.charAt(i), rest, result);
    }
}

Each call fixes one more character and recurses on the rest; when nothing remains, the prefix is a complete permutation. For the empty string that happens immediately, so the list holds one empty string, printed as []. There are n! results, so keep inputs small.

Classes and objects

These practice Classes and Objects, Encapsulation, Records, Enums, Sealed Classes, Pattern Matching and The Object Class.

18. A safe bank account (Beginner)

Complete BankAccount so the balance can never become invalid. deposit and withdraw throw IllegalArgumentException("Amount must be positive: " + amount) for amounts of zero or less; withdraw throws IllegalStateException when the balance is too small, with the message shown in the comments.

Java Exercise 18: Bank account

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
class BankAccount {
    private double balance;

    void deposit(double amount) {
        requirePositive(amount);
        balance += amount;
    }

    void withdraw(double amount) {
        requirePositive(amount);
        if (amount > balance) {
            throw new IllegalStateException(
                "Insufficient funds: balance %.2f, requested %.2f".formatted(balance, amount));
        }
        balance -= amount;
    }

    double balance() {
        return balance;
    }

    private static void requirePositive(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Amount must be positive: " + amount);
        }
    }
}

Because the field is private, these two methods are the only way to change it, so the checks can't be bypassed. Validate before changing state, so a failed call leaves the account untouched. Real money code would use long cents or BigDecimal instead of double.

19. Areas with a sealed hierarchy (Intermediate)

Complete area with a switch pattern over the sealed Shape interface (no default branch), and compute the total area of the list.

Java Exercise 19: Sealed shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
double area(Shape shape) {
    return switch (shape) {
        case Circle c -> Math.PI * c.radius() * c.radius();
        case Rectangle(double w, double h) -> w * h;
        case Triangle(double b, double h) -> 0.5 * b * h;
    };
}

// in main:
double total = shapes.stream().mapToDouble(this::area).sum();
System.out.printf("Total: %.2f%n", total);

Since Shape is sealed, the compiler checks that the switch covers all three records, so no default is needed, and adding a fourth shape would turn this switch into a compile error until you handle it. this::area works because area is an instance method of the compact file's implicit class.

20. A validated Money record (Intermediate)

Complete the Money record: the compact constructor rejects negative amounts and currencies that aren't three uppercase letters; plus adds two amounts of the same currency and throws otherwise; toString prints like EUR 12.50.

Java Exercise 20: Money record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
record Money(long cents, String currency) {
    Money {
        Objects.requireNonNull(currency, "currency");
        if (cents < 0) throw new IllegalArgumentException("negative amount: " + cents);
        if (!currency.matches("[A-Z]{3}")) throw new IllegalArgumentException("bad currency: " + currency);
    }

    Money plus(Money other) {
        if (!currency.equals(other.currency)) {
            throw new IllegalArgumentException("currency mismatch: " + currency + " vs " + other.currency);
        }
        return new Money(Math.addExact(cents, other.cents), currency);
    }

    @Override
    public String toString() {
        return "%s %d.%02d".formatted(currency, cents / 100, cents % 100);
    }
}

A compact constructor runs before the fields are assigned, so no invalid Money can ever exist. Storing whole cents in a long avoids floating-point rounding, and Math.addExact turns a silent overflow into an exception.

21. Traffic light enum (Beginner)

Complete next() so each light switches to the following one in the cycle RED โ†’ GREEN โ†’ YELLOW โ†’ RED, and print the total length of one cycle using values().

Java Exercise 21: Traffic light enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
Light next() {
    Light[] all = values();
    return all[(ordinal() + 1) % all.length];
}

// in main:
int cycle = 0;
for (Light l : Light.values()) cycle += l.seconds();
IO.println("Cycle: " + cycle + " s");

values() returns the constants in declaration order and ordinal() is each constant's position, so % length wraps YELLOW back to RED. A switch returning the next constant works too and doesn't depend on the declaration order.

22. equals and hashCode (Intermediate)

The set below should contain 2 points, because two of them have the same coordinates, but it prints 3. Add equals and hashCode to Point (keep it a class, not a record) so that the set and contains work.

Java Exercise 22: equals and hashCode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    return o instanceof Point other && x == other.x && y == other.y;
}

@Override
public int hashCode() {
    return Objects.hash(x, y);
}

HashSet first compares hash codes and only then calls equals, so both methods must agree: equal points must return the same hash. The instanceof pattern also handles null, since null instanceof Point is false.

Exceptions

These practice Exceptions, Throwing Exceptions and Custom Exceptions.

23. Parsing ages with a custom exception (Intermediate)

Write parseAge(String text) that returns the age for valid input (0 to 150, surrounding spaces allowed). Otherwise it throws the checked InvalidAgeException, keeping the original NumberFormatException as the cause when the text isn't a number.

Java Exercise 23: Custom exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
int parseAge(String text) throws InvalidAgeException {
    int age;
    try {
        age = Integer.parseInt(text.strip());
    } catch (NumberFormatException e) {
        throw new InvalidAgeException("not a number: " + text, e);
    }
    if (age < 0 || age > 150) {
        throw new InvalidAgeException("age out of range: " + age, null);
    }
    return age;
}

This is exception translation: callers deal with one meaningful, checked type instead of a low-level parsing error, and the cause keeps the original stack trace for debugging.

Collections

These practice HashMap, HashSet, Queues and Deques, LinkedHashMap, TreeMap and Comparable and Comparator.

24. Top words (Intermediate)

Write topWords(String text, int k) that returns the k most frequent words (lowercase), most frequent first, breaking ties alphabetically.

Java Exercise 24: Top words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
List<String> topWords(String text, int k) {
    Map<String, Integer> counts = new HashMap<>();
    for (String word : text.toLowerCase().split("\\W+")) {
        if (!word.isEmpty()) counts.merge(word, 1, Integer::sum);
    }
    return counts.entrySet().stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
                .thenComparing(Map.Entry.comparingByKey()))
        .limit(k)
        .map(Map.Entry::getKey)
        .toList();
}

merge counts in one line, and the two-level comparator sorts by count (descending) and then by word. Splitting "" gives one empty string, which the isEmpty check skips.

25. Balanced brackets (Intermediate)

Write isBalanced(String text) that checks whether every (, [ and { is closed by the matching bracket in the right order. Other characters are ignored. Use an ArrayDeque as a stack.

Java Exercise 25: Balanced brackets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
boolean isBalanced(String text) {
    Deque<Character> stack = new ArrayDeque<>();
    for (char c : text.toCharArray()) {
        switch (c) {
            case '(' -> stack.push(')');
            case '[' -> stack.push(']');
            case '{' -> stack.push('}');
            case ')', ']', '}' -> {
                if (stack.isEmpty() || stack.pop() != c) return false;
            }
            default -> { }
        }
    }
    return stack.isEmpty();
}

Pushing the expected closing bracket makes the check a simple comparison. An empty stack at a closer means an extra closer, and a non-empty stack at the end means something was never closed.

26. Group anagrams (Intermediate)

Write groupAnagrams(List<String> words) that groups words made of the same letters. Use the word's sorted letters as the key, keep the keys sorted, and keep each group's words in input order.

Java Exercise 26: Group anagrams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
Map<String, List<String>> groupAnagrams(List<String> words) {
    Map<String, List<String>> groups = new TreeMap<>();
    for (String word : words) {
        char[] letters = word.toCharArray();
        Arrays.sort(letters);
        groups.computeIfAbsent(new String(letters), key -> new ArrayList<>()).add(word);
    }
    return groups;
}

All anagrams share the same sorted letters, so they land under the same key. computeIfAbsent creates each list the first time a key appears, and the TreeMap keeps keys sorted.

27. An LRU cache (Advanced)

Complete LruCache so it holds at most capacity entries and, when full, evicts the least recently used one (reads count as use). Extend LinkedHashMap in access-order mode.

Java Exercise 27: LRU cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
class LruCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;

    LruCache(int capacity) {
        super(16, 0.75f, true);          // true = access order
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }
}

With accessOrder = true, every get or put moves the entry to the end, so the "eldest" entry is the least recently used one. put calls removeEldestEntry after each insertion, and returning true removes it.

Generics, lambdas and streams

These practice Generics, Bounded Types and Wildcards, Lambdas, Streams and Collecting Stream Results.

28. A generic maxBy (Intermediate)

Write the generic method maxBy(List<T> items, Comparator<? super T> order) that returns the largest element as an Optional, or an empty Optional for an empty list. Don't use streams.

Java Exercise 28: Generic maxBy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
<T> Optional<T> maxBy(List<T> items, Comparator<? super T> order) {
    if (items.isEmpty()) return Optional.empty();
    T best = items.getFirst();
    for (T item : items) {
        if (order.compare(item, best) > 0) best = item;
    }
    return Optional.of(best);
}

The ? super T wildcard lets callers pass a more general comparator, for example a Comparator<Object> or a comparator written for a superclass. getFirst() comes from sequenced collections (Java 21); items.get(0) is the classic spelling.

29. Department report with streams (Advanced)

Using only streams and collectors, print the average salary per department (departments sorted by name), the highest-paid employee, and each department's employee names joined with commas.

Java Exercise 29: Stream report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
Map<String, Double> averages = staff.stream()
    .collect(Collectors.groupingBy(Employee::department, TreeMap::new,
             Collectors.averagingDouble(Employee::salary)));
IO.println(averages);

staff.stream()
    .max(Comparator.comparingDouble(Employee::salary))
    .ifPresent(top -> IO.println("Top earner: " + top.name()));

Map<String, String> names = staff.stream()
    .collect(Collectors.groupingBy(Employee::department, TreeMap::new,
             Collectors.mapping(Employee::name, Collectors.joining(", "))));
IO.println(names);

groupingBy takes a map factory (TreeMap::new for sorted keys) and a downstream collector that decides what each group becomes: an average, or names joined into one string.

Concurrency

These practice Executors and Thread Pools and Threads.

30. Parallel sum with an executor (Advanced)

Sum the numbers 1 to 1,000,000 by splitting the range into 4 chunks, submitting each chunk as a Callable<Long> to a fixed thread pool of 4 threads, and adding up the Future results. Shut the pool down properly.

Java Exercise 30: Parallel sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Show solution
Java
long parallelSum(int n, int chunks) throws Exception {
    try (ExecutorService pool = Executors.newFixedThreadPool(chunks)) {
        List<Future<Long>> parts = new ArrayList<>();
        int size = (n + chunks - 1) / chunks;            // round up
        for (int start = 1; start <= n; start += size) {
            int from = start, to = Math.min(n, start + size - 1);
            parts.add(pool.submit(() -> {
                long sum = 0;
                for (int i = from; i <= to; i++) sum += i;
                return sum;
            }));
        }
        long total = 0;
        for (Future<Long> part : parts) total += part.get();
        return total;
    }
}

Each task gets its own range, so the threads share nothing and need no locks. from and to are fresh effectively final variables for each lambda to capture, and since Java 19 ExecutorService is AutoCloseable: try-with-resources shuts the pool down and waits for its tasks.

Where to go next

Finished them all? Take a solution you're proud of and make it better: add input validation, write a JUnit test for it, or rewrite a loop as a stream (or the reverse) and compare readability. Then try a larger project such as the Bank Account System, where these pieces have to work together.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Exercise 5, why use Math.floorMod(c - 'a' + shift, 26) instead of (c - 'a' + shift) % 26?

    In Java, -2 % 26 is -2, but Math.floorMod(-2, 26) is 24. floorMod always returns a value between 0 and 25 for a positive divisor, which is exactly the range of letter indexes.
  2. 2. In Exercise 22, what happens if you override equals but not hashCode?

    HashSet uses hashCode to choose a bucket and only calls equals for entries in that bucket. The default hashCode is per object, so equal points almost never meet, and the duplicate gets in.
  3. 3. In Exercise 27, what does passing true as the third argument to the LinkedHashMap constructor do?

    With accessOrder = true, get and put move the entry to the end, so the first (eldest) entry is the least recently used. removeEldestEntry then decides whether to evict it.
  4. 4. Why does Exercise 15 compute half once and return half * half instead of power(base, n / 2) * power(base, n / 2)?

    Two recursive calls at each level double the work at each of the log n levels, which adds up to about n calls again. Reusing the half result keeps it to about log2 n multiplications.

Summary

  • The exercises cover the whole course in order: basics and formatting, strings, control flow, arrays, methods and recursion, classes, records, enums, sealed types, exceptions, collections, generics, streams and concurrency.
  • Recurring techniques: % and / for digits and time, two-pointer and read/write indexes for arrays, maps with merge/computeIfAbsent for counting and grouping, a stack for nesting, and recursion that shrinks the problem each call.
  • Good solutions validate input first, keep state private, give errors clear messages and pick the right collection.
  • When you finish an exercise, test the edge cases: empty input, zero, negatives, duplicates and very large values.

Next: Java Interview Questions, where you'll review the concepts interviewers ask about most, from string immutability to the memory model.