TExcelTAD
Home › Java › Java Exercises

Java Exercises

Time to put everything together. Each exercise has a starter playground that already compiles and runs — the parts you need to write are marked with TODO. Edit the code, press ▶ Run, and compare your output with the expected result in the task description. When you're stuck, peek at the solution, but give it a real try first: a little struggle is what makes knowledge stick.

Tip: The output block under each starter shows what the unfinished starter prints. The task text tells you what the finished program should print.

Exercise 1: FizzBuzz

For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number itself otherwise. The finished program prints 1, 2, Fizz, 4, Buzz, ... 14, FizzBuzz — one value per line.

java · try it yourself
class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            // TODO: print Fizz, Buzz, FizzBuzz or the number
            System.out.println(i);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Show solution
java
class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            if (i % 15 == 0) {
                System.out.println("FizzBuzz");
            } else if (i % 3 == 0) {
                System.out.println("Fizz");
            } else if (i % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(i);
            }
        }
    }
}

Checking i % 15 first matters: a multiple of 15 is also a multiple of 3, so testing % 3 first would print Fizz instead of FizzBuzz.

Exercise 2: Reverse words

Complete reverseWords so that it reverses the order of the words in a sentence (not the letters). "Java is really fun" should become "fun really is Java".

java · try it yourself
class Main {
    static String reverseWords(String sentence) {
        // TODO: split the sentence into words and join them in reverse order
        return sentence;
    }

    public static void main(String[] args) {
        System.out.println(reverseWords("Java is really fun"));
        System.out.println(reverseWords("one"));
    }
}
Java is really fun
one
Show solution
java
class Main {
    static String reverseWords(String sentence) {
        String[] words = sentence.trim().split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            sb.append(words[i]);
            if (i > 0) sb.append(' ');
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(reverseWords("Java is really fun"));
        System.out.println(reverseWords("one"));
    }
}

Splitting on \\s+ handles several spaces between words. An alternative is Collections.reverse(Arrays.asList(words)) followed by String.join(" ", words).

Exercise 3: Array statistics

Write min, max and average for an int[] without using Arrays or streams. For the data below the finished program prints min=3 max=42 avg=17.6.

java · try it yourself
class Main {
    static int min(int[] a) {
        return 0; // TODO
    }

    static int max(int[] a) {
        return 0; // TODO
    }

    static double average(int[] a) {
        return 0; // TODO
    }

    public static void main(String[] args) {
        int[] data = {12, 3, 42, 7, 24};
        System.out.println("min=" + min(data) + " max=" + max(data) + " avg=" + average(data));
    }
}
min=0 max=0 avg=0.0
Show solution
java
class Main {
    static int min(int[] a) {
        int m = a[0];
        for (int x : a) if (x < m) m = x;
        return m;
    }

    static int max(int[] a) {
        int m = a[0];
        for (int x : a) if (x > m) m = x;
        return m;
    }

    static double average(int[] a) {
        int sum = 0;
        for (int x : a) sum += x;
        return (double) sum / a.length;
    }

    public static void main(String[] args) {
        int[] data = {12, 3, 42, 7, 24};
        System.out.println("min=" + min(data) + " max=" + max(data) + " avg=" + average(data));
    }
}

Start min and max with the first element rather than 0 — otherwise an array of only negative (or only large) numbers gives the wrong answer. The cast to double avoids integer division in average.

Exercise 4: Palindrome checker

A palindrome reads the same forwards and backwards, ignoring case, spaces and punctuation. Complete isPalindrome. The finished program prints true, true, false.

java · try it yourself
class Main {
    static boolean isPalindrome(String text) {
        // TODO: keep only letters/digits in lower case, then compare from both ends
        return false;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Racecar"));
        System.out.println(isPalindrome("A man, a plan, a canal: Panama"));
        System.out.println(isPalindrome("Java"));
    }
}
false
false
false
Show solution
java
class Main {
    static boolean isPalindrome(String text) {
        String clean = text.toLowerCase().replaceAll("[^a-z0-9]", "");
        int left = 0, right = clean.length() - 1;
        while (left < right) {
            if (clean.charAt(left) != clean.charAt(right)) return false;
            left++;
            right--;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Racecar"));
        System.out.println(isPalindrome("A man, a plan, a canal: Panama"));
        System.out.println(isPalindrome("Java"));
    }
}

The two-pointer loop stops as soon as a mismatch is found and never builds a reversed copy. new StringBuilder(clean).reverse().toString().equals(clean) is a shorter alternative.

Exercise 5: Word frequency

Count how often each word appears (ignoring case) and print the words in alphabetical order with their counts. The finished program prints:

and: 1
cat: 2
dog: 1
the: 3
distinct words: 4
java · try it yourself
import java.util.Map;
import java.util.TreeMap;

class Main {
    public static void main(String[] args) {
        String text = "The cat and the dog saw the cat";
        Map<String, Integer> counts = new TreeMap<>();
        // TODO: split the text, lower-case each word and count it in the map
        // TODO: skip the word "saw" (we only care about nouns and articles)
        counts.forEach((word, n) -> System.out.println(word + ": " + n));
        System.out.println("distinct words: " + counts.size());
    }
}
distinct words: 0
Show solution
java
import java.util.Map;
import java.util.TreeMap;

class Main {
    public static void main(String[] args) {
        String text = "The cat and the dog saw the cat";
        Map<String, Integer> counts = new TreeMap<>();
        for (String w : text.toLowerCase().split(" ")) {
            if (w.equals("saw")) continue;
            counts.merge(w, 1, Integer::sum);
        }
        counts.forEach((word, n) -> System.out.println(word + ": " + n));
        System.out.println("distinct words: " + counts.size());
    }
}

A TreeMap keeps the keys sorted, so no extra sorting step is needed. merge(w, 1, Integer::sum) inserts 1 for a new word or adds 1 to the existing count.

Exercise 6: Bank account class

Complete the Account class: deposit adds a positive amount, withdraw subtracts it only if the balance is sufficient and returns whether it succeeded, and toString returns "<owner>: <balance>". The finished program prints:

true
false
Mia: 70.0
java · try it yourself
class Account {
    private final String owner;
    private double balance;

    Account(String owner) {
        this.owner = owner;
    }

    void deposit(double amount) {
        // TODO: only accept positive amounts
    }

    boolean withdraw(double amount) {
        // TODO: refuse if amount <= 0 or amount > balance
        return false;
    }

    @Override
    public String toString() {
        return "TODO";
    }
}

class Main {
    public static void main(String[] args) {
        Account acc = new Account("Mia");
        acc.deposit(100);
        acc.deposit(-20);
        System.out.println(acc.withdraw(30));
        System.out.println(acc.withdraw(500));
        System.out.println(acc);
    }
}
false
false
TODO
Show solution
java
class Account {
    private final String owner;
    private double balance;

    Account(String owner) {
        this.owner = owner;
    }

    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    boolean withdraw(double amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }

    @Override
    public String toString() {
        return owner + ": " + balance;
    }
}

class Main {
    public static void main(String[] args) {
        Account acc = new Account("Mia");
        acc.deposit(100);
        acc.deposit(-20);
        System.out.println(acc.withdraw(30));
        System.out.println(acc.withdraw(500));
        System.out.println(acc);
    }
}

Because balance is private, the only way to change it is through deposit and withdraw, which enforce the rules — that's encapsulation at work.

Exercise 7: Shapes with an interface

Create two records, Circle(double r) and Square(double side), that implement the Shape interface. Then make main print the total area of all shapes, formatted with two decimals: Total area: 37.57.

java · try it yourself
import java.util.List;

interface Shape {
    double area();
}

// TODO: record Circle(double r) implements Shape { ... }
// TODO: record Square(double side) implements Shape { ... }

class Main {
    public static void main(String[] args) {
        List<Shape> shapes = List.of(
            // TODO: new Circle(2), new Square(5)
        );
        double total = 0;
        // TODO: add up the areas
        System.out.printf("Total area: %.2f%n", total);
    }
}
Total area: 0.00
Show solution
java
import java.util.List;

interface Shape {
    double area();
}

record Circle(double r) implements Shape {
    public double area() { return Math.PI * r * r; }
}

record Square(double side) implements Shape {
    public double area() { return side * side; }
}

class Main {
    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Circle(2), new Square(5));
        double total = 0;
        for (Shape s : shapes) total += s.area();
        System.out.printf("Total area: %.2f%n", total);
    }
}

The loop only knows about Shape; each record supplies its own area() — polymorphism through an interface. With streams: shapes.stream().mapToDouble(Shape::area).sum().

Exercise 8: Stream pipeline

Given a list of products, use one stream pipeline to print the names of products that cost less than 20, sorted by price (cheapest first), in upper case, joined with ", ". The finished program prints CABLE, MOUSE, NOTEBOOK.

java · try it yourself
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

record Product(String name, double price) { }

class Main {
    public static void main(String[] args) {
        List<Product> products = List.of(
            new Product("Keyboard", 49.0),
            new Product("Notebook", 15.5),
            new Product("Cable", 4.99),
            new Product("Monitor", 189.0),
            new Product("Mouse", 12.0));

        String result = products.stream()
                // TODO: filter, sort, map and join
                .map(Product::name)
                .collect(Collectors.joining(", "));
        System.out.println(result);
    }
}
Keyboard, Notebook, Cable, Monitor, Mouse
Show solution
java
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

record Product(String name, double price) { }

class Main {
    public static void main(String[] args) {
        List<Product> products = List.of(
            new Product("Keyboard", 49.0),
            new Product("Notebook", 15.5),
            new Product("Cable", 4.99),
            new Product("Monitor", 189.0),
            new Product("Mouse", 12.0));

        String result = products.stream()
                .filter(p -> p.price() < 20)
                .sorted(Comparator.comparingDouble(Product::price))
                .map(p -> p.name().toUpperCase())
                .collect(Collectors.joining(", "));
        System.out.println(result);
    }
}

The order of operations matters: sort while you still have Product objects (with prices), and only then map to names.

Exercise 9: Safe parsing with exceptions

Complete parseAll so that it converts every string to an int, skips invalid entries, and records them in the errors list. The finished program prints:

[12, 7, 30]
Invalid: [abc, 4.5]
java · try it yourself
import java.util.ArrayList;
import java.util.List;

class Main {
    static List<Integer> parseAll(List<String> inputs, List<String> errors) {
        List<Integer> result = new ArrayList<>();
        for (String s : inputs) {
            // TODO: try Integer.parseInt(s); on NumberFormatException add s to errors
        }
        return result;
    }

    public static void main(String[] args) {
        List<String> errors = new ArrayList<>();
        List<Integer> numbers = parseAll(List.of("12", "abc", "7", "4.5", "30"), errors);
        System.out.println(numbers);
        System.out.println("Invalid: " + errors);
    }
}
[]
Invalid: []
Show solution
java
import java.util.ArrayList;
import java.util.List;

class Main {
    static List<Integer> parseAll(List<String> inputs, List<String> errors) {
        List<Integer> result = new ArrayList<>();
        for (String s : inputs) {
            try {
                result.add(Integer.parseInt(s));
            } catch (NumberFormatException e) {
                errors.add(s);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<String> errors = new ArrayList<>();
        List<Integer> numbers = parseAll(List.of("12", "abc", "7", "4.5", "30"), errors);
        System.out.println(numbers);
        System.out.println("Invalid: " + errors);
    }
}

The try block wraps only the one risky call, so a bad entry skips just that element and the loop carries on.

Exercise 10: Recursive sum of digits

Write a recursive method digitSum(int n) that returns the sum of the digits of a non-negative number — no loops allowed. digitSum(9045) is 18. The finished program prints 18, 0 and 1.

java · try it yourself
class Main {
    static int digitSum(int n) {
        // TODO: base case for n < 10, otherwise last digit + digitSum(rest)
        return 0;
    }

    public static void main(String[] args) {
        System.out.println(digitSum(9045));
        System.out.println(digitSum(0));
        System.out.println(digitSum(1000));
    }
}
0
0
0
Show solution
java
class Main {
    static int digitSum(int n) {
        if (n < 10) return n;                 // a single digit is its own sum
        return n % 10 + digitSum(n / 10);     // last digit + sum of the rest
    }

    public static void main(String[] args) {
        System.out.println(digitSum(9045));
        System.out.println(digitSum(0));
        System.out.println(digitSum(1000));
    }
}

Each call removes the last digit with n / 10, so the input shrinks until it reaches a single digit — the base case.

Test yourself

In FizzBuzz, why must the % 15 check come before % 3 and % 5?

  1. It is faster
  2. Multiples of 15 would otherwise match % 3 first and print Fizz
  3. Java requires it
  4. It doesn't matter

Why should min start with a[0] instead of 0?

  1. Arrays start at index 0
  2. 0 might be smaller than every element, giving a wrong minimum
  3. It is required by the compiler
  4. To avoid an exception

Which map type keeps word counts in alphabetical order automatically?

  1. HashMap
  2. TreeMap
  3. LinkedHashMap
  4. EnumMap