Java Exercises

Practise what you've learned. Type the missing piece into each highlighted gap and press Check. Further down are programming challenges with editors and model solutions — copy them to run locally.

Fill in the blanks

Basics

Print a line of text.

System.out.("Hello, Java!");

Declare a whole-number variable.

 age = 30;

Make the variable a constant.

 double VAT_RATE = 0.23;

Let the compiler infer the type.

 city = "Lisbon";

Write a long literal larger than an int can hold.

long population = 8_100_000_000;

Convert a double to an int, dropping the decimals.

int whole = () 9.99;

Turn the text "42" into a number.

int n = Integer.("42");

Get the remainder of a division.

int r = 17  5;

Compare two strings by their contents.

if (answer.("yes")) { }

Format a number with two decimal places.

String s = "%".formatted(3.14159);

Control flow

Run the block only when the condition is false.

if (stock > 0) { sell(); }  { reorder(); }

Give a value from a switch block.

case "L" -> { double base = 3.0;  base + 0.7; }

Loop through every element of an array.

for (String name  names) { System.out.println(name); }

Skip to the next repetition.

if (i % 2 == 0) ;

Get the number of elements in an array.

int n = scores.;

Methods and objects

Declare a method that returns nothing.

 greet(String name) { System.out.println("Hi " + name); }

Accept any number of int arguments.

int sum(int numbers) { }

Create a new object.

Product p =  Product("Mug", 12.5);

Refer to the current object's field.

.name = name;

Make a field shared by all objects of the class.

 int count = 0;

Hide a field from other classes.

 double balance;

Inherit from another class.

class Dog  Animal { }

Call the superclass constructor.

Dog(String name) { (name); }

Check that you are really overriding a method.

 public String toString() { return "Dog"; }

Promise to provide an interface's methods.

class Invoice  Payable { }

Declare an immutable data class in one line.

 Point(int x, int y) {}

Exceptions, collections and modern Java

Handle a failure.

try { parse(text); }  (NumberFormatException e) { useDefault(); }

Raise an exception.

 new IllegalArgumentException("Negative amount");

Create a resizable list of strings.

List<String> names = new <>();

Read a map value with a fallback.

int qty = stock.("lamp", 0);

Keep only even numbers in a stream.

nums.stream().(n -> n % 2 == 0).toList();

Transform each element of a stream.

names.stream().(String::toUpperCase).toList();

Group employees by department.

staff.stream().collect(Collectors.(Employee::department));

Supply a default when the Optional is empty.

String name = findName(id).("unknown");

Close the resource automatically.

 (BufferedReader r = Files.newBufferedReader(path)) { }

Programming challenges

1. FizzBuzz

Print the numbers 1 to 15, but "Fizz" for multiples of 3, "Buzz" for multiples of 5 and "FizzBuzz" for both.

Try it yourself · Main.java
Edit the code, copy it into Main.java and run java Main.java (Java 25+). How to set up Java
Show a model solution
JAVA
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            String out = i % 15 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : String.valueOf(i);
            System.out.print(out + " ");
        }
        System.out.println();
    }
}
Output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

2. Word frequency

Count how often each word appears in a sentence (ignoring case) and print the words alphabetically with their counts.

Try it yourself · Main.java
Edit the code, copy it into Main.java and run java Main.java (Java 25+). How to set up Java
Show a model solution
JAVA
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        String text = "The cat and the hat and THE bat";
        Map<String, Integer> counts = new TreeMap<>();
        for (String w : text.toLowerCase().split("\\s+")) {
            counts.merge(w, 1, Integer::sum);
        }
        counts.forEach((w, n) -> System.out.println(w + " " + n));
    }
}
Output
and 2
bat 1
cat 1
hat 1
the 3

3. A bank account class

Write an Account class with a private balance, deposit and withdraw methods that reject invalid amounts, and a transaction count.

Try it yourself · Main.java
Edit the code, copy it into Main.java and run java Main.java (Java 25+). How to set up Java
Show a model solution
JAVA
class Account {
    private double balance;
    private int transactions;

    void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("Deposit must be positive");
        balance += amount;
        transactions++;
    }

    void withdraw(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("Withdrawal must be positive");
        if (amount > balance) throw new IllegalStateException("Insufficient funds");
        balance -= amount;
        transactions++;
    }

    double balance() { return balance; }
    int transactions() { return transactions; }
}

public class Main {
    public static void main(String[] args) {
        Account acc = new Account();
        acc.deposit(100);
        acc.withdraw(30);
        try {
            acc.withdraw(500);
        } catch (IllegalStateException e) {
            System.out.println("Refused: " + e.getMessage());
        }
        System.out.println(acc.balance() + " after " + acc.transactions() + " transactions");
    }
}
Output
Refused: Insufficient funds
70.0 after 2 transactions

4. Student report with streams

Given student records with a name and score, print the average, the top student, and the names of everyone who passed (score ≥ 50) in alphabetical order.

Try it yourself · Main.java
Edit the code, copy it into Main.java and run java Main.java (Java 25+). How to set up Java
Show a model solution
JAVA
import java.util.Comparator;
import java.util.List;

record Student(String name, int score) {}

public class Main {
    public static void main(String[] args) {
        List<Student> students = List.of(
            new Student("Iris", 82), new Student("Omar", 45),
            new Student("Lena", 91), new Student("Kai", 67)
        );
        double avg = students.stream().mapToInt(Student::score).average().orElse(0);
        String top = students.stream().max(Comparator.comparingInt(Student::score)).map(Student::name).orElse("-");
        List<String> passed = students.stream().filter(s -> s.score() >= 50).map(Student::name).sorted().toList();
        System.out.println("Average: %.2f".formatted(avg));
        System.out.println("Top: " + top);
        System.out.println("Passed: " + passed);
    }
}
Output
Average: 71.25
Top: Lena
Passed: [Iris, Kai, Lena]

5. Shapes with a sealed interface

Model Circle, Square and Triangle (base and height) as records implementing a sealed Shape, and compute the total area with a pattern-matching switch.

Try it yourself · Main.java
Edit the code, copy it into Main.java and run java Main.java (Java 25+). How to set up Java
Show a model solution
JAVA
import java.util.List;

sealed interface Shape permits Circle, Square, Triangle {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {}

public class Main {
    static double area(Shape s) {
        return switch (s) {
            case Circle(double r) -> Math.PI * r * r;
            case Square(double side) -> side * side;
            case Triangle(double b, double h) -> b * h / 2;
        };
    }

    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Circle(1), new Square(2), new Triangle(3, 4));
        double total = shapes.stream().mapToDouble(Main::area).sum();
        System.out.println("Total area: %.2f".formatted(total));
    }
}
Output
Total area: 13.14