Java

Core Java Practice Problems with Solutions

15 core Java practice problems with full solutions and real output: strings, arrays, OOP, collections, exceptions and streams, graded from easy to hard.

Practice.java1int sum = 0;2for (int n : numbers) {3 if (n % 2 == 0) sum += n;4}5// sum of even numbers
  • Java
  • Practice
  • Beginners

Quick answer: Good core Java practice problems cover loops, strings, arrays, OOP, collections, exceptions and streams. Work through these 15 in order, from counting digits and rotating arrays to a bank account class, equals and hashCode, sorting objects and stream grouping. Try each one for 20 minutes before you read its solution, then rewrite it the next day.

These core Java practice problems take you from simple loops to the kind of code a fresher interview expects. There are 15, in four levels. Each one has a complete class you can run, the exact output, and a short note on the idea behind it.

Many lists stop at palindromes and prime numbers. Those are useful, but Java interviews go further. They ask about objects, equals and hashCode, collections, exceptions and streams. More than half of this list is about those topics.

How to use these core Java exercises

Every solution was compiled and run on Java 17. Save each class in a file with the same name, such as DigitCount.java, then run:

javac DigitCount.java
java DigitCount

Follow the same four steps each time:

  1. Read the problem and write one input and its expected output on paper.
  2. Code it yourself for 20 minutes. A rough version that works is fine.
  3. Compare with the solution. Look for one thing you did differently.
  4. Write it again the next day from a blank file.

If Java is not installed yet, start with our install Java guide.

Pro tip: Before you code, list two odd inputs, such as an empty array or a negative number. Then test them. This habit finds many bugs early.

Level 1: Core Java practice problems on loops and strings

1. Count the digits in a number

Count how many digits an integer has. 0 has one digit, and the minus sign does not count.

public class DigitCount {
    static int countDigits(int n) {
        int count = 0;
        do {
            count++;
            n /= 10;
        } while (n != 0);
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countDigits(90210));
        System.out.println(countDigits(0));
        System.out.println(countDigits(-47));
    }
}
5
1
2

A do-while loop runs at least once, so 0 is counted correctly. With a plain while (n != 0) loop, 0 would give the wrong answer, 0.

2. Reverse each word in a sentence

Reverse the letters of every word but keep the words in order. "code in java" becomes "edoc ni avaj".

public class ReverseWords {
    static String reverseWords(String text) {
        StringBuilder out = new StringBuilder();
        for (String word : text.trim().split("\\s+")) {
            if (out.length() > 0) {
                out.append(' ');
            }
            out.append(new StringBuilder(word).reverse());
        }
        return out.toString();
    }

    public static void main(String[] args) {
        System.out.println(reverseWords("code in java"));
        System.out.println(reverseWords("  extra   spaces "));
    }
}
edoc ni avaj
artxe secaps

split("\\s+") treats any run of spaces as one gap. StringBuilder changes its own content, while joining a String with + in a loop makes a new object each time. Read more in our Java strings lesson.

3. Print a number pyramid

Print a pyramid with four rows, where row n counts from 1 to n.

public class NumberPyramid {
    public static void main(String[] args) {
        int rows = 4;
        for (int row = 1; row <= rows; row++) {
            StringBuilder line = new StringBuilder(" ".repeat(rows - row));
            for (int n = 1; n <= row; n++) {
                line.append(n);
                if (n < row) {
                    line.append(' ');
                }
            }
            System.out.println(line);
        }
    }
}
   1
  1 2
 1 2 3
1 2 3 4

The outer loop picks the row. The inner loop fills it. The number of leading spaces is rows - row, which shrinks by one each time. Most pattern questions come down to finding one such formula.

4. Check an Armstrong number

Raise each digit to the power of the number of digits and add the results. If you get the same number back, it is an Armstrong number. For example, 153 = 1³ + 5³ + 3³. Print all of them from 100 to 9999.

public class Armstrong {
    static boolean isArmstrong(int n) {
        int digits = String.valueOf(n).length();
        long sum = 0;
        for (int rest = n; rest > 0; rest /= 10) {
            int digit = rest % 10;
            long power = 1;
            for (int i = 0; i < digits; i++) {
                power *= digit;
            }
            sum += power;
        }
        return sum == n;
    }

    public static void main(String[] args) {
        for (int n = 100; n < 10000; n++) {
            if (isArmstrong(n)) {
                System.out.println(n);
            }
        }
    }
}
153
370
371
407
1634
8208
9474

The code multiplies in a loop and does not use Math.pow. Math.pow returns a double, and whole numbers are safer when you need an exact match.

Level 2: Arrays

5. Rotate an array to the right

Move every element k places to the right. Elements that fall off the end come back at the start.

import java.util.Arrays;

public class RotateArray {
    static void rotate(int[] a, int k) {
        if (a.length == 0) {
            return;
        }
        k %= a.length;
        reverse(a, 0, a.length - 1);
        reverse(a, 0, k - 1);
        reverse(a, k, a.length - 1);
    }

    static void reverse(int[] a, int left, int right) {
        while (left < right) {
            int temp = a[left];
            a[left++] = a[right];
            a[right--] = temp;
        }
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        rotate(a, 7);
        System.out.println(Arrays.toString(a));
    }
}
[4, 5, 1, 2, 3]

Rotating five items by 7 is the same as rotating by 2, which is why k %= a.length comes first. Three reversals do the job with no second array. The method expects k to be zero or more.

6. Largest sum of neighbours

Find the largest sum of any run of neighbouring elements. The array has at least one element. This is known as Kadane's algorithm.

public class MaxSubarray {
    static int maxSum(int[] a) {
        int current = a[0];
        int best = a[0];
        for (int i = 1; i < a.length; i++) {
            current = Math.max(a[i], current + a[i]);
            best = Math.max(best, current);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(maxSum(new int[]{4, -6, 5, -1, 3, -8, 2}));
        System.out.println(maxSum(new int[]{-5, -2, -9}));
    }
}
7
-2

At each element you choose: extend the current run, or start fresh here. The best run in the first example is 5, -1, 3. Starting best at a[0], and not at 0, makes the all-negative case work.

7. Merge two sorted arrays

Combine two sorted arrays into one sorted array without calling Arrays.sort.

import java.util.Arrays;

public class MergeSorted {
    static int[] merge(int[] a, int[] b) {
        int[] out = new int[a.length + b.length];
        int i = 0, j = 0, k = 0;
        while (i < a.length && j < b.length) {
            out[k++] = a[i] <= b[j] ? a[i++] : b[j++];
        }
        while (i < a.length) {
            out[k++] = a[i++];
        }
        while (j < b.length) {
            out[k++] = b[j++];
        }
        return out;
    }

    public static void main(String[] args) {
        int[] merged = merge(new int[]{2, 5, 9}, new int[]{1, 5, 7, 12});
        System.out.println(Arrays.toString(merged));
    }
}
[1, 2, 5, 5, 7, 9, 12]

Two indexes walk through the arrays and always take the smaller value. The last two loops copy whatever is left over. This is the key step inside merge sort.

Common mistake: Forgetting the two leftover loops. The first loop stops as soon as one array runs out, so the result ends with zeros where the remaining values should be.

Level 3: OOP and exceptions

8. A bank account that protects its balance

Write an account class that refuses bad deposits and overdrawn withdrawals with clear errors.

public class BankDemo {
    static class LowBalanceException extends Exception {
        LowBalanceException(String message) {
            super(message);
        }
    }

    static class Account {
        private long balance;

        void deposit(long amount) {
            checkPositive(amount);
            balance += amount;
        }

        void withdraw(long amount) throws LowBalanceException {
            checkPositive(amount);
            if (amount > balance) {
                throw new LowBalanceException("Short by " + (amount - balance));
            }
            balance -= amount;
        }

        private void checkPositive(long amount) {
            if (amount <= 0) {
                throw new IllegalArgumentException("Amount must be positive");
            }
        }

        long getBalance() {
            return balance;
        }
    }

    public static void main(String[] args) {
        Account account = new Account();
        account.deposit(1000);
        try {
            account.withdraw(300);
            account.withdraw(900);
        } catch (LowBalanceException e) {
            System.out.println("Failed: " + e.getMessage());
        }
        System.out.println("Balance: " + account.getBalance());
    }
}
Failed: Short by 200
Balance: 700

balance is private, so outside code can change it only through checked methods. Low balance is a normal event the caller should handle, so it is a checked exception. A negative amount is a coding bug, so it is unchecked. See checked vs unchecked exceptions.

9. Shapes with an interface

Print the total area of a mixed list of shapes without using any instanceof check.

import java.util.List;

public class ShapeDemo {
    interface Shape {
        double area();
    }

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

    record Rectangle(double width, double height) implements Shape {
        public double area() {
            return width * height;
        }
    }

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

The loop does not know which shape it holds. Java picks the right area() at run time. That is polymorphism, and it means a new Triangle needs no change to the loop.

10. Make a Set treat two objects as equal

Two students with the same roll number should count as one entry in a HashSet.

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class StudentSet {
    static class Student {
        private final String rollNo;
        private final String name;

        Student(String rollNo, String name) {
            this.rollNo = rollNo;
            this.name = name;
        }

        @Override
        public boolean equals(Object other) {
            return other instanceof Student s && rollNo.equals(s.rollNo);
        }

        @Override
        public int hashCode() {
            return Objects.hash(rollNo);
        }

        @Override
        public String toString() {
            return rollNo + ":" + name;
        }
    }

    public static void main(String[] args) {
        Set<Student> set = new HashSet<>();
        System.out.println(set.add(new Student("A1", "Ravi")));
        System.out.println(set.add(new Student("A1", "Ravi Kumar")));
        System.out.println(set);
    }
}
true
false
[A1:Ravi]

The second add returns false and the first object stays. Remove hashCode and run it again. The set will almost always keep both, because the two students now have different hash codes.

Interview note: "Why must you override hashCode when you override equals?" is a very common Java interview question. This program is your answer. Practise it with our equals and hashCode lesson.

Level 4: Core Java problems and solutions with collections and streams

11. First letter that does not repeat

Return the first character that appears only once in a string.

import java.util.LinkedHashMap;
import java.util.Map;

public class FirstUnique {
    static Character firstUnique(String text) {
        Map<Character, Integer> counts = new LinkedHashMap<>();
        for (char c : text.toCharArray()) {
            counts.merge(c, 1, Integer::sum);
        }
        for (Map.Entry<Character, Integer> e : counts.entrySet()) {
            if (e.getValue() == 1) {
                return e.getKey();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(firstUnique("swiss"));
        System.out.println(firstUnique("aabb"));
    }
}
w
null

LinkedHashMap remembers the order in which keys were added. A plain HashMap does not promise any order, so it could return the wrong letter.

12. Check balanced brackets

Say whether every bracket in a string is closed in the right order.

import java.util.ArrayDeque;
import java.util.Deque;

public class Brackets {
    static boolean isBalanced(String text) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char c : text.toCharArray()) {
            switch (c) {
                case '(' -> stack.push(')');
                case '[' -> stack.push(']');
                case '{' -> stack.push('}');
                case ')', ']', '}' -> {
                    if (stack.isEmpty() || stack.pop() != c) {
                        return false;
                    }
                }
                default -> { }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isBalanced("{a[b(c)]}"));
        System.out.println(isBalanced("(]"));
        System.out.println(isBalanced("((("));
    }
}
true
false
false

The trick is to push the closing bracket you expect. Then a closing bracket must simply match the top of the stack. The final isEmpty() check catches brackets that were never closed.

13. Sort employees by two fields

Sort by department from A to Z, then by salary from high to low.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortEmployees {
    record Employee(String name, String dept, int salary) { }

    public static void main(String[] args) {
        List<Employee> list = new ArrayList<>(List.of(
                new Employee("Asha", "QA", 40000),
                new Employee("Imran", "Dev", 52000),
                new Employee("Divya", "Dev", 61000),
                new Employee("John", "QA", 45000)));

        list.sort(Comparator.comparing(Employee::dept)
                .thenComparing(Employee::salary, Comparator.reverseOrder()));

        list.forEach(e -> System.out.println(
                e.dept() + " " + e.name() + " " + e.salary()));
    }
}
Dev Divya 61000
Dev Imran 52000
QA John 45000
QA Asha 40000

List.of gives a list you cannot change, so the code copies it into an ArrayList before sorting. Passing reverseOrder() to thenComparing reverses only the salary. Calling .reversed() at the end would reverse the department order too.

14. Group and average with streams

Find the average marks for each branch.

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class BranchAverage {
    record Result(String branch, int marks) { }

    public static void main(String[] args) {
        List<Result> results = List.of(
                new Result("ECE", 70), new Result("CSE", 85),
                new Result("ECE", 81), new Result("CSE", 90));

        Map<String, Double> averages = results.stream()
                .collect(Collectors.groupingBy(
                        Result::branch,
                        TreeMap::new,
                        Collectors.averagingInt(Result::marks)));

        System.out.println(averages);
    }
}
{CSE=87.5, ECE=75.5}

groupingBy makes the groups, and averagingInt works on each group. TreeMap::new keeps the branches in alphabetical order. The same shape answers many Java streams interview questions.

15. A small cache that drops the oldest item

Keep only the three most recently used entries.

import java.util.LinkedHashMap;
import java.util.Map;

public class SmallCache {
    static class LruCache<K, V> extends LinkedHashMap<K, V> {
        private final int limit;

        LruCache(int limit) {
            super(16, 0.75f, true);
            this.limit = limit;
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > limit;
        }
    }

    public static void main(String[] args) {
        LruCache<String, Integer> cache = new LruCache<>(3);
        cache.put("a", 1);
        cache.put("b", 2);
        cache.put("c", 3);
        cache.get("a");
        cache.put("d", 4);
        System.out.println(cache.keySet());
    }
}
[c, a, d]

The third constructor value, true, orders entries by last use and not by insertion. Reading a makes it recent, so b becomes the oldest and is dropped when d arrives.

A two-week core Java coding practice plan

Days Problems Extra task
1 to 3 1 to 4 Write two more pattern programs of your own
4 to 6 5 to 7 Test with empty and one-element arrays
7 to 9 8 to 10 Add a savings account that extends Account
10 to 13 11 to 15 Redo problem 14 with a plain loop and a map
14 Any five, from a blank file Explain each one aloud in two minutes

After that, our page on how long to learn Core Java shows where practice fits in a full study plan, and Java coding interview questions gives you harder problems.

From practice problems to projects

Small problems teach you the pieces. A project teaches you to join them. Combine problems 8, 13 and 14 into one console app: store students in a HashMap, throw an exception for a duplicate roll number, sort the list and print branch averages.

In CodeBegun's Java Full Stack with AI course, Core Java is followed by SQL, Hibernate and Spring Boot. The first of the six projects is a Core Java console app called StudentHub CLI. The Java full stack course guide lists every module and project.

Frequently asked questions

How many Core Java problems should I solve before learning Spring Boot?

Aim for about 60 to 80 small problems spread across strings, arrays, OOP, collections and exceptions. The number matters less than being able to solve a new easy problem without looking at notes.

Which Java version do these solutions need?

All 15 were compiled and run on Java 17. Some use records, pattern matching and switch arrows, so Java 17 or newer is the simplest choice.

Should I use an IDE or a plain text editor for practice?

Use an IDE such as IntelliJ IDEA for daily work, but write a few programs a week in a plain editor. Many coding tests give little or no auto-complete, so you need to remember the syntax.

Are Core Java exercises enough for fresher interviews?

They cover a large part of the Core Java and coding rounds. You also need SQL, a project you can explain, and for full stack roles some Spring Boot and React.

What should I do when my program gives the wrong output?

Run it by hand on paper with the smallest failing input, writing down each variable after each line. Then use the debugger to confirm. Reading the solution before doing this skips the part that teaches you most.


Want someone to review how you solve these? Book a free demo class in Madhapur or live online, or see the Java Full Stack with AI course.

Found this useful? Share it: LinkedIn Facebook WhatsApp

Written by

Siva Prasad Galaba

Staff Engineer & Founder, CodeBegun

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaching the next generation to code the way the industry actually works.

Back to all articles
Chat with us