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!");
println adds a line break; print doesn't (lesson 03).
Declare a whole-number variable.
age = 30;
(lesson 05)
Make the variable a constant.
double VAT_RATE = 0.23;
final variables can't be reassigned (lesson 05).
Let the compiler infer the type.
city = "Lisbon";
(lesson 05)
Write a long literal larger than an int can hold.
long population = 8_100_000_000;
(lesson 06)
Convert a double to an int, dropping the decimals.
int whole = () 9.99;
Casting truncates (lesson 07).
Turn the text "42" into a number.
int n = Integer.("42");
(lesson 07)
Get the remainder of a division.
int r = 17 5;
(lesson 08)
Compare two strings by their contents.
if (answer.("yes")) { }
Never use == for string contents (lesson 09).
Format a number with two decimal places.
String s = "%".formatted(3.14159);
(lesson 10)
Control flow
Run the block only when the condition is false.
if (stock > 0) { sell(); } { reorder(); }
(lesson 13)
Give a value from a switch block.
case "L" -> { double base = 3.0; base + 0.7; }
(lesson 14)
Loop through every element of an array.
for (String name names) { System.out.println(name); }
The for-each loop (lesson 16).
Skip to the next repetition.
if (i % 2 == 0) ;
(lesson 17)
Get the number of elements in an array.
int n = scores.;
length is a field on arrays — no parentheses (lesson 18).
Methods and objects
Declare a method that returns nothing.
greet(String name) { System.out.println("Hi " + name); }
(lesson 20)
Accept any number of int arguments.
int sum(int numbers) { }
Varargs (lesson 21).
Create a new object.
Product p = Product("Mug", 12.5);
(lesson 25)
Refer to the current object's field.
.name = name;
(lesson 23)
Make a field shared by all objects of the class.
int count = 0;
(lesson 24)
Hide a field from other classes.
double balance;
(lesson 26)
Inherit from another class.
class Dog Animal { }
(lesson 28)
Call the superclass constructor.
Dog(String name) { (name); }
(lesson 28)
Check that you are really overriding a method.
public String toString() { return "Dog"; }
(lesson 29)
Promise to provide an interface's methods.
class Invoice Payable { }
(lesson 31)
Declare an immutable data class in one line.
Point(int x, int y) {}
(lesson 32)
Exceptions, collections and modern Java
Handle a failure.
try { parse(text); } (NumberFormatException e) { useDefault(); }
(lesson 36)
Raise an exception.
new IllegalArgumentException("Negative amount");
(lesson 36)
Create a resizable list of strings.
List<String> names = new <>();
(lesson 40)
Read a map value with a fallback.
int qty = stock.("lamp", 0);
(lesson 42)
Keep only even numbers in a stream.
nums.stream().(n -> n % 2 == 0).toList();
(lesson 46)
Transform each element of a stream.
names.stream().(String::toUpperCase).toList();
(lesson 46)
Group employees by department.
staff.stream().collect(Collectors.(Employee::department));
(lesson 47)
Supply a default when the Optional is empty.
String name = findName(id).("unknown");
(lesson 48)
Close the resource automatically.
(BufferedReader r = Files.newBufferedReader(path)) { }
try-with-resources (lesson 37).
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.
Show a model solution
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(); } }
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.
Show a model solution
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)); } }
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.
Show a model solution
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"); } }
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.
Show a model solution
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); } }
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.
Show a model solution
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)); } }
Total area: 13.14