{jsonbody.com}

Top 23 Java Coding Interview Questions

Top 23 Java coding interview questions with solutions: string and array programs, collections, Java 8 streams, OOP, multithreading and classic programs.

Loading…

String Programs

Q1. Reverse a string

Problem: Reverse a string without using StringBuilder.reverse().

static String reverse(String s) {
    char[] chars = s.toCharArray();
    for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
        char tmp = chars[i];
        chars[i] = chars[j];
        chars[j] = tmp;
    }
    return new String(chars);
}

Explanation: Swap characters from both ends moving inward. In real code, new StringBuilder(s).reverse().toString() is simpler.

Q2. Check whether a string is a palindrome

Problem: Return true if a string reads the same both ways, ignoring case.

static boolean isPalindrome(String s) {
    String clean = s.toLowerCase().replaceAll("[^a-z0-9]", "");
    int left = 0, right = clean.length() - 1;
    while (left < right) {
        if (clean.charAt(left++) != clean.charAt(right--)) return false;
    }
    return true;
}

Explanation: Clean the input, then compare characters with two pointers. This uses O(1) extra space after cleaning.

Q3. Count the occurrences of each character

Problem: Print how many times each character appears in a string.

static Map<Character, Long> charCount(String s) {
    return s.chars()
            .mapToObj(c -> (char) c)
            .collect(Collectors.groupingBy(
                    Function.identity(), LinkedHashMap::new, Collectors.counting()));
}

// charCount("banana") -> {b=1, a=3, n=2}

Explanation: The stream groups characters and counts each group. LinkedHashMap keeps the order in which characters first appear.

Q4. Find the first non-repeating character

Problem: Return the first character that appears only once.

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

Explanation: merge increments each count, and LinkedHashMap keeps insertion order, so the first entry with a count of one is the answer.

Q5. Check whether two strings are anagrams

Problem: Return true if two strings use the same letters.

static boolean isAnagram(String a, String b) {
    if (a.length() != b.length()) return false;
    int[] count = new int[26];
    for (int i = 0; i < a.length(); i++) {
        count[a.charAt(i) - 'a']++;
        count[b.charAt(i) - 'a']--;
    }
    for (int c : count) if (c != 0) return false;
    return true;
}

Explanation: For lowercase English letters, a 26-slot array counts up for one string and down for the other. Every slot ends at zero for anagrams.

Q6. Remove duplicate characters

Problem: Remove repeated characters, keeping the first occurrence.

static String removeDuplicates(String s) {
    StringBuilder sb = new StringBuilder();
    Set<Character> seen = new HashSet<>();
    for (char c : s.toCharArray()) {
        if (seen.add(c)) sb.append(c);
    }
    return sb.toString();
}

// removeDuplicates("programming") -> "progamin"

Explanation: Set.add returns false if the character is already present, so it both checks and records in one call.

Array Programs

Q7. Find the second largest element

Problem: Return the second largest distinct number in an array.

static int secondLargest(int[] nums) {
    int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
    for (int n : nums) {
        if (n > first) {
            second = first;
            first = n;
        } else if (n > second && n != first) {
            second = n;
        }
    }
    return second;
}

Explanation: Track the top two values in one pass. Skipping values equal to the maximum keeps the second value distinct.

Q8. Find the missing number from 1 to n

Problem: An array holds 1 to n with one number missing. Find it.

static int missingNumber(int[] nums) {
    int n = nums.length + 1;
    long expected = (long) n * (n + 1) / 2;
    long actual = 0;
    for (int x : nums) actual += x;
    return (int) (expected - actual);
}

Explanation: Subtract the actual sum from n(n+1)/2. Using long avoids overflow for large n.

Q9. Move zeros to the end

Problem: Move every 0 to the end of the array, keeping the order of the other numbers.

static void moveZeros(int[] nums) {
    int insert = 0;
    for (int n : nums) if (n != 0) nums[insert++] = n;
    while (insert < nums.length) nums[insert++] = 0;
}

Explanation: Write non-zero values forward with a pointer, then fill the rest with zeros. One pass, no extra array.

Q10. Find duplicate elements

Problem: Print the values that appear more than once.

static Set<Integer> duplicates(int[] nums) {
    Set<Integer> seen = new HashSet<>();
    Set<Integer> dupes = new LinkedHashSet<>();
    for (int n : nums) {
        if (!seen.add(n)) dupes.add(n);
    }
    return dupes;
}

Explanation: When add fails, the value was seen before, so record it as a duplicate. This runs in O(n).

Q11. Two Sum

Problem: Return the indexes of two numbers that add up to a target.

static int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> seen = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        Integer j = seen.get(target - nums[i]);
        if (j != null) return new int[] { j, i };
        seen.put(nums[i], i);
    }
    return new int[0];
}

Explanation: Store each value's index and check whether the complement is already in the map. O(n) time and space.

Q12. Merge two sorted arrays

Problem: Combine two sorted arrays into one sorted array.

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

Explanation: Take the smaller front element each time, then copy what remains. This is the merge step of merge sort, O(n + m).

Java 8 Streams

Q13. Find even numbers and square them

Problem: From a list of integers, return the squares of the even numbers.

List<Integer> result = numbers.stream()
        .filter(n -> n % 2 == 0)
        .map(n -> n * n)
        .toList();

Explanation: filter keeps the even numbers and map squares them. toList() (Java 16+) returns an unmodifiable list.

Q14. Find the highest salary per department

Problem: Given employees, return the highest-paid employee in each department.

Map<String, Optional<Employee>> top = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary))));

Explanation: groupingBy splits employees by department and maxBy keeps the top salary in each group.

Q15. Find the second highest number with streams

Problem: Return the second highest distinct number in a list.

Optional<Integer> second = numbers.stream()
        .distinct()
        .sorted(Comparator.reverseOrder())
        .skip(1)
        .findFirst();

Explanation: Remove duplicates, sort descending, skip the top value and take the next. It returns an empty Optional if there is no second value.

Q16. Count words by frequency

Problem: Count how many times each word appears in a sentence.

Map<String, Long> counts = Arrays.stream(text.toLowerCase().split("\\s+"))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Explanation: Split on whitespace, then group identical words and count them. The regex \\s+ matches one or more spaces.

Q17. Join names into one string

Problem: Join a list of names as "Asha, Ravi, Meera".

String joined = names.stream()
        .map(String::trim)
        .collect(Collectors.joining(", "));

Explanation: Collectors.joining concatenates with a separator, and optionally a prefix and suffix such as "[" and "]".

Q18. Partition numbers into even and odd

Problem: Split a list into even and odd numbers.

Map<Boolean, List<Integer>> parts = numbers.stream()
        .collect(Collectors.partitioningBy(n -> n % 2 == 0));

List<Integer> evens = parts.get(true);
List<Integer> odds = parts.get(false);

Explanation: partitioningBy always returns a map with true and false keys, unlike groupingBy.

OOP & Multithreading

Q19. Implement a thread-safe singleton

Problem: Create a singleton that is lazily created and safe with many threads.

public class Config {
    private Config() {}

    private static class Holder {
        private static final Config INSTANCE = new Config();
    }

    public static Config getInstance() {
        return Holder.INSTANCE;
    }
}

Explanation: The holder class loads only on the first call to getInstance, and class loading is thread-safe, so no locks are needed. An enum singleton is another safe option.

Q20. Create an immutable class

Problem: Write an immutable Money class.

public final class Money {
    private final String currency;
    private final long amount;

    public Money(String currency, long amount) {
        this.currency = currency;
        this.amount = amount;
    }

    public Money add(long more) {
        return new Money(currency, amount + more);
    }

    public String getCurrency() { return currency; }
    public long getAmount() { return amount; }
}

// Java 16+: record Money(String currency, long amount) {}

Explanation: The class is final, fields are private final, there are no setters, and changes return a new object. A record gives the same result in one line.

Q21. Print odd and even numbers with two threads

Problem: Two threads print 1 to 10 in order, one printing odd numbers and one even.

class OddEven {
    private int n = 1;
    private final int max = 10;

    synchronized void print(boolean odd) throws InterruptedException {
        while (n <= max) {
            while ((n % 2 == 1) != odd) wait();
            if (n <= max) System.out.println(Thread.currentThread().getName() + ": " + n++);
            notifyAll();
        }
    }
}

OddEven p = new OddEven();
new Thread(() -> { try { p.print(true); } catch (InterruptedException ignored) {} }, "odd").start();
new Thread(() -> { try { p.print(false); } catch (InterruptedException ignored) {} }, "even").start();

Explanation: Each thread waits until it is its turn, prints, then wakes the other with notifyAll. Checking the condition in a while loop guards against spurious wake-ups.

Q22. Implement a producer-consumer

Problem: One thread produces items and another consumes them through a bounded buffer.

BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);

Thread producer = new Thread(() -> {
    try {
        for (int i = 1; i <= 10; i++) queue.put(i);
    } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});

Thread consumer = new Thread(() -> {
    try {
        for (int i = 1; i <= 10; i++) System.out.println("Consumed " + queue.take());
    } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});

producer.start();
consumer.start();

Explanation: put blocks when the queue is full and take blocks when it is empty, so BlockingQueue handles all the waiting for you.

Q23. Run tasks with an ExecutorService

Problem: Run several tasks in a thread pool and collect their results.

ExecutorService pool = Executors.newFixedThreadPool(4);
try {
    List<Callable<Integer>> tasks = List.of(() -> 1, () -> 2, () -> 3);
    int sum = 0;
    for (Future<Integer> f : pool.invokeAll(tasks)) sum += f.get();
    System.out.println(sum); // 6
} finally {
    pool.shutdown();
}

Explanation: invokeAll runs every task and waits for them. Always shut the pool down, or its threads keep the JVM alive. Java 21's Executors.newVirtualThreadPerTaskExecutor() suits many I/O tasks.