Java Examples and Exercises

These Java examples bring together everything in the tutorial. Try to solve each exercise yourself before reading the solution, then compare your approach and output.

Exercise 1: FizzBuzz

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

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 

Exercise 2: Palindromes and Primes

Write isPalindrome, which ignores case and non-letters, and isPrime, which checks divisors only up to the square root.

import java.util.stream.IntStream;

public class Main {
    static boolean isPalindrome(String s) {
        String clean = s.toLowerCase().replaceAll("[^a-z]", "");
        return new StringBuilder(clean).reverse().toString().equals(clean);
    }

    static boolean isPrime(int n) {
        if (n < 2) return false;
        for (int d = 2; d * d <= n; d++) {
            if (n % d == 0) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Never odd or even"));
        System.out.println(isPalindrome("Java"));
        System.out.println(IntStream.rangeClosed(1, 30).filter(Main::isPrime).boxed().toList());
    }
}
true
false
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Exercise 3: Word Frequency

Count how often each word appears in a sentence and print the top three.

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

public class Main {
    public static void main(String[] args) {
        String text = "to be or not to be that is the question to ask";
        Map<String, Long> freq = Arrays.stream(text.split("\\s+"))
                .collect(Collectors.groupingBy(w -> w, Collectors.counting()));
        freq.entrySet().stream()
            .sorted(Map.Entry.<String, Long>comparingByValue().reversed()
                    .thenComparing(Map.Entry.comparingByKey()))
            .limit(3)
            .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
    }
}
to: 3
be: 2
ask: 1

Exercise 4: Mini Library App

This small program combines a record, an enum, a class with encapsulated state, exceptions and streams.

import java.util.*;

enum Genre { FICTION, SCIENCE, HISTORY }

record Book(String title, Genre genre, int year) {}

class Library {
    private final List<Book> books = new ArrayList<>();
    private final Set<String> borrowed = new HashSet<>();

    void add(Book b) { books.add(b); }

    void borrow(String title) {
        boolean exists = books.stream().anyMatch(b -> b.title().equals(title));
        if (!exists) throw new NoSuchElementException("No book: " + title);
        if (!borrowed.add(title)) throw new IllegalStateException(title + " is already out");
        System.out.println("Borrowed " + title);
    }

    List<Book> available(Genre genre) {
        return books.stream()
                .filter(b -> b.genre() == genre && !borrowed.contains(b.title()))
                .sorted(Comparator.comparingInt(Book::year))
                .toList();
    }
}

public class Main {
    public static void main(String[] args) {
        var lib = new Library();
        lib.add(new Book("Dune", Genre.FICTION, 1965));
        lib.add(new Book("Cosmos", Genre.SCIENCE, 1980));
        lib.add(new Book("Neuromancer", Genre.FICTION, 1984));

        lib.borrow("Dune");
        try {
            lib.borrow("Dune");
        } catch (IllegalStateException e) {
            System.out.println("Error: " + e.getMessage());
        }
        System.out.println(lib.available(Genre.FICTION));
    }
}
Borrowed Dune
Error: Dune is already out
[Book[title=Neuromancer, genre=FICTION, year=1984]]

More Exercises to Try

  • Write a method that reverses an int array in place without creating a new array.
  • Build a Student record and print the average grade per class using groupingBy and averagingDouble.
  • Create a Stack<T> generic class backed by an ArrayList with push, pop and peek.
  • Add a return method to the Library and throw an exception when returning a book that was not borrowed.
  • Write a temperature converter using an enum Unit { CELSIUS, FAHRENHEIT } and a switch expression.

Where to Go Next

You now know core Java. Good next steps are unit testing with JUnit 5, a build tool such as Maven or Gradle, the java.time API for dates, and then a framework like Spring Boot to build REST APIs and web applications.

Frequently asked questions

What are good Java projects for beginners?

A to-do list, a bank account simulator, a library or inventory system, a quiz game, or a simple REST API with Spring Boot. Start small and add features step by step.

How long does it take to learn Java?

Most people learn the basics in 4 to 8 weeks of regular practice. Becoming job-ready with frameworks and tools usually takes several months.

Where can I practise Java coding problems?

Sites like Exercism, LeetCode, HackerRank and Codewars have Java tracks. Solving a few small problems each day is one of the fastest ways to improve.