Java course
java programming language icon

Java Exercises: 26 Practice Problems with Solutions

Java rewards precision. These problems cover types and control flow, arrays, collections, methods, classes, inheritance, interfaces and exceptions — the ground covered by most first-year courses and entry-level interviews.

Each solution is a complete program with a Main class, so you can paste it straight into the editor and run it. Problems that read input tell you what to type in the Input box.

Run your answer here

Type your solution, press Run, and use the Input box when a problem asks you to read from standard input.

Java Compiler
Output
Code runs on the Play with Coding execution engine — your code is saved locally for next time.

How to practise so it actually sticks

Attempt the problem before opening the solution, even if your first version is clumsy. A working ugly answer teaches more than a beautiful one you read. When you get stuck for more than five minutes, read the hint — not the solution — and try again.

After you pass, open the solution and ask what is different about it. Shorter? Fewer variables? A built-in you did not know? That comparison is where most of the growth happens. Then change the problem slightly: sort the other direction, handle an empty input, read a value instead of hard-coding it.

Aim for three to five problems a day rather than thirty in one sitting. Spacing practice over days is what moves syntax from "I can look it up" to "my fingers know it".

The exercises

Showing 26 of 26 exercises.

  1. BeginnerBasics & output

    1. Print a greeting

    Store the name "Ada" in a String and print "Hello, Ada!".

    Hint: String concatenation with + works fine here.

    public class Main {
        public static void main(String[] args) {
            String name = ;
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            String name = "Ada";
            System.out.println("Hello, " + name + "!");
        }
    }
  2. BeginnerBasics & output

    2. Primitive types

    Declare an int, a double, a char and a boolean and print them on one line.

    Hint: char literals use single quotes.

    public class Main {
        public static void main(String[] args) {
            
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            int i = 42;
            double d = 3.14;
            char c = 'J';
            boolean b = true;
            System.out.println(i + " " + d + " " + c + " " + b);
        }
    }
  3. BeginnerBasics & output

    3. Read input with Scanner

    Read a name from standard input and greet the user. Type a name in the Input box before running.

    Hint: new Scanner(System.in).nextLine().

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            
        }
    }
    Show solution
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String name = sc.nextLine();
            System.out.println("Hello, " + name + "!");
        }
    }
  4. BeginnerConditionals

    4. Even or odd

    Print "even" or "odd" for the number 17.

    Hint: Use % and an if/else.

    public class Main {
        public static void main(String[] args) {
            int n = 17;
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            int n = 17;
            System.out.println(n % 2 == 0 ? "even" : "odd");
        }
    }
  5. BeginnerConditionals

    5. Grade from a score

    Print A for 90+, B for 80+, C for 70+, otherwise F. Test with 84.

    Hint: Chain else if branches from highest to lowest.

    public class Main {
        public static void main(String[] args) {
            int score = 84;
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            int score = 84;
            if (score >= 90) System.out.println("A");
            else if (score >= 80) System.out.println("B");
            else if (score >= 70) System.out.println("C");
            else System.out.println("F");
        }
    }
  6. BeginnerConditionals

    6. Switch on a day number

    Print the weekday name for 3 using a switch statement.

    Hint: Remember break, or use the arrow form.

    public class Main {
        public static void main(String[] args) {
            int day = 3;
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            int day = 3;
            switch (day) {
                case 1 -> System.out.println("Monday");
                case 2 -> System.out.println("Tuesday");
                case 3 -> System.out.println("Wednesday");
                default -> System.out.println("Later in the week");
            }
        }
    }
  7. BeginnerLoops

    7. FizzBuzz to 20

    Print 1..20 replacing multiples of 3 with "Fizz", 5 with "Buzz", both with "FizzBuzz".

    Hint: Test the multiple of 15 first.

    public class Main {
        public static void main(String[] args) {
            for (int i = 1; i <= 20; i++) {
            }
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            for (int i = 1; i <= 20; 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);
            }
        }
    }
  8. BeginnerLoops

    8. Factorial with a loop

    Compute 10! with a loop and print it.

    Hint: Use a long so it does not overflow.

    public class Main {
        public static void main(String[] args) {
            long result = 1;
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            long result = 1;
            for (int i = 2; i <= 10; i++) result *= i;
            System.out.println(result);
        }
    }
  9. BeginnerLoops

    9. Print a triangle

    Print a right-angled triangle of five rows of stars.

    Hint: Nested loops: rows outside, stars inside.

    public class Main {
        public static void main(String[] args) {
            
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            for (int i = 1; i <= 5; i++) {
                StringBuilder row = new StringBuilder();
                for (int j = 0; j < i; j++) row.append("*");
                System.out.println(row);
            }
        }
    }
  10. BeginnerStrings

    10. Reverse a string

    Reverse "java" and print the result.

    Hint: new StringBuilder(s).reverse().

    public class Main {
        public static void main(String[] args) {
            String s = "java";
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            String s = "java";
            System.out.println(new StringBuilder(s).reverse());
        }
    }
  11. IntermediateStrings

    11. Palindrome check

    Check whether "Never odd or even" is a palindrome, ignoring case and non-letters.

    Hint: replaceAll("[^a-z]", "") after toLowerCase().

    public class Main {
        public static void main(String[] args) {
            String s = "Never odd or even";
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            String s = "Never odd or even";
            String t = s.toLowerCase().replaceAll("[^a-z0-9]", "");
            System.out.println(t.equals(new StringBuilder(t).reverse().toString()));
        }
    }
  12. IntermediateStrings

    12. Count words

    Count the words in "the quick brown fox jumps" and print the count.

    Hint: split("\\s+").length.

    public class Main {
        public static void main(String[] args) {
            String s = "the quick brown fox jumps";
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            String s = "the quick brown fox jumps";
            System.out.println(s.split("\\s+").length);
        }
    }
  13. BeginnerArrays

    13. Array statistics

    For {4, 9, 1, 7, 3} print the sum, the maximum and the minimum.

    Hint: Track running values inside a for-each loop.

    public class Main {
        public static void main(String[] args) {
            int[] nums = {4, 9, 1, 7, 3};
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            int[] nums = {4, 9, 1, 7, 3};
            int sum = 0, max = nums[0], min = nums[0];
            for (int n : nums) {
                sum += n;
                if (n > max) max = n;
                if (n < min) min = n;
            }
            System.out.println(sum + " " + max + " " + min);
        }
    }
  14. IntermediateArrays

    14. Sort and search an array

    Sort {5, 2, 9, 1} with Arrays.sort and print the array, then binary search for 9.

    Hint: Arrays.toString and Arrays.binarySearch.

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[] nums = {5, 2, 9, 1};
        }
    }
    Show solution
    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[] nums = {5, 2, 9, 1};
            Arrays.sort(nums);
            System.out.println(Arrays.toString(nums));
            System.out.println(Arrays.binarySearch(nums, 9));
        }
    }
  15. IntermediateCollections

    15. Work with an ArrayList

    Add four names to an ArrayList, remove one and print the rest sorted.

    Hint: Collections.sort or list.sort(null).

    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            
        }
    }
    Show solution
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            List<String> names = new ArrayList<>(List.of("Zoe", "Ada", "Ben", "Cy"));
            names.remove("Ben");
            Collections.sort(names);
            System.out.println(names);
        }
    }
  16. IntermediateCollections

    16. Count with a HashMap

    Count how often each word appears in "to be or not to be".

    Hint: map.merge(word, 1, Integer::sum).

    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            
        }
    }
    Show solution
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            String[] words = "to be or not to be".split(" ");
            Map<String, Integer> counts = new HashMap<>();
            for (String w : words) counts.merge(w, 1, Integer::sum);
            System.out.println(counts);
        }
    }
  17. AdvancedCollections

    17. Filter and sum with streams

    From 1..20 keep the even numbers, square them and print the total using streams.

    Hint: IntStream.rangeClosed(1, 20).filter(...).map(...).sum().

    import java.util.stream.IntStream;
    
    public class Main {
        public static void main(String[] args) {
            
        }
    }
    Show solution
    import java.util.stream.IntStream;
    
    public class Main {
        public static void main(String[] args) {
            int total = IntStream.rangeClosed(1, 20).filter(n -> n % 2 == 0).map(n -> n * n).sum();
            System.out.println(total);
        }
    }
  18. BeginnerMethods

    18. Write and overload methods

    Write add(int, int) and add(double, double) and call both.

    Hint: Overloads differ by parameter types.

    public class Main {
        public static void main(String[] args) {
        }
    }
    Show solution
    public class Main {
        static int add(int a, int b) { return a + b; }
        static double add(double a, double b) { return a + b; }
    
        public static void main(String[] args) {
            System.out.println(add(2, 3) + " " + add(2.5, 3.5));
        }
    }
  19. IntermediateMethods

    19. Recursive Fibonacci

    Write a recursive fib(n) and print the first ten Fibonacci numbers.

    Hint: Base cases: fib(0) = 0, fib(1) = 1.

    public class Main {
        public static void main(String[] args) {
        }
    }
    Show solution
    public class Main {
        static int fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
    
        public static void main(String[] args) {
            for (int i = 0; i < 10; i++) System.out.print(fib(i) + " ");
            System.out.println();
        }
    }
  20. IntermediateClasses & OOP

    20. A class with encapsulation

    Write a BankAccount class with a private balance, deposit, withdraw and a getter.

    Hint: Refuse withdrawals larger than the balance.

    Show solution
    class BankAccount {
        private double balance;
        void deposit(double n) { balance += n; }
        void withdraw(double n) {
            if (n > balance) throw new IllegalArgumentException("Insufficient funds");
            balance -= n;
        }
        double getBalance() { return balance; }
    }
    
    public class Main {
        public static void main(String[] args) {
            BankAccount acc = new BankAccount();
            acc.deposit(100);
            acc.withdraw(30);
            System.out.println(acc.getBalance());
        }
    }
  21. IntermediateClasses & OOP

    21. Inheritance and overriding

    Write an abstract Shape with area(), then Square and Circle subclasses, and print both areas.

    Hint: Use @Override on the subclass methods.

    Show solution
    abstract class Shape {
        abstract double area();
    }
    class Square extends Shape {
        private final double side;
        Square(double side) { this.side = side; }
        @Override double area() { return side * side; }
    }
    class Circle extends Shape {
        private final double r;
        Circle(double r) { this.r = r; }
        @Override double area() { return Math.PI * r * r; }
    }
    
    public class Main {
        public static void main(String[] args) {
            Shape[] shapes = { new Square(3), new Circle(1) };
            for (Shape s : shapes) System.out.printf("%.2f%n", s.area());
        }
    }
  22. AdvancedClasses & OOP

    22. Program to an interface

    Define interface Greeter with greet(String) and two implementations, then call both through the interface.

    Hint: A lambda can implement a single-method interface.

    Show solution
    interface Greeter {
        String greet(String name);
    }
    
    public class Main {
        public static void main(String[] args) {
            Greeter formal = n -> "Good evening, " + n + ".";
            Greeter casual = n -> "Hey " + n + "!";
            System.out.println(formal.greet("Ada"));
            System.out.println(casual.greet("Ada"));
        }
    }
  23. IntermediateExceptions

    23. Catch an exception

    Parse "12x" with Integer.parseInt inside try/catch and print a friendly message.

    Hint: It throws NumberFormatException.

    public class Main {
        public static void main(String[] args) {
            
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            try {
                System.out.println(Integer.parseInt("12x"));
            } catch (NumberFormatException e) {
                System.out.println("That is not a whole number: " + e.getMessage());
            }
        }
    }
  24. AdvancedExceptions

    24. Throw a custom exception

    Create InvalidAgeException and throw it when an age is negative, then catch and report it.

    Hint: Extend Exception and call super(message).

    Show solution
    class InvalidAgeException extends Exception {
        InvalidAgeException(String msg) { super(msg); }
    }
    
    public class Main {
        static void check(int age) throws InvalidAgeException {
            if (age < 0) throw new InvalidAgeException("Age cannot be " + age);
        }
    
        public static void main(String[] args) {
            try {
                check(-5);
            } catch (InvalidAgeException e) {
                System.out.println("Rejected: " + e.getMessage());
            }
        }
    }
  25. AdvancedAlgorithms

    25. Bubble sort by hand

    Sort {5, 1, 4, 2, 8} with bubble sort and print each pass.

    Hint: Swap neighbours while any swap still happens.

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[] a = {5, 1, 4, 2, 8};
        }
    }
    Show solution
    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[] a = {5, 1, 4, 2, 8};
            for (int i = 0; i < a.length - 1; i++) {
                for (int j = 0; j < a.length - 1 - i; j++) {
                    if (a[j] > a[j + 1]) {
                        int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
                    }
                }
                System.out.println(Arrays.toString(a));
            }
        }
    }
  26. AdvancedAlgorithms

    26. Primes below 50

    Print every prime number below 50.

    Hint: Only test divisors up to the square root.

    public class Main {
        public static void main(String[] args) {
            
        }
    }
    Show solution
    public class Main {
        public static void main(String[] args) {
            for (int n = 2; n < 50; n++) {
                boolean prime = true;
                for (int d = 2; d * d <= n; d++) {
                    if (n % d == 0) { prime = false; break; }
                }
                if (prime) System.out.print(n + " ");
            }
            System.out.println();
        }
    }

What to do next

If a whole topic feels shaky, go back to that chapter in the 17-chapter Java course and re-read it, then return here. When the advanced problems feel routine, take the final Java quiz and claim your certificate, or open the Java online compiler and build something of your own.