java coding interview questions prepared as printed solutions for a code walkthrough
Blog/10 Java Coding Questions to Practise With Tests and Follow-Ups
Shayan Naji

Shayan Naji

12 min read

10 Java Coding Questions to Practise With Tests and Follow-Ups

Practise Java coding interview questions by writing a small correct solution, testing its boundaries, and explaining the trade-offs aloud. Start with strings, arrays, and collections, then add streams and concurrency if your role calls for them. The ten exercises below give you a defined problem, an approach to defend, and a follow-up that checks whether you understand your code.

These are original practice exercises, not a claim about any employer's question bank. Use Java 8-compatible syntax for the examples, confirm the interview environment separately, and put the imports from each snippet above your practice class. You can also print your solutions and mark failed cases on paper before retyping them from memory.

Which Java coding questions should you practise first?

For a junior interview, concentrate on string traversal, array boundaries, collection choice, and explaining runtime. For an experienced role, keep those foundations and add duplicate-key handling, shared mutable state, and the consequences of changing a contract. Ask the recruiter whether the round includes algorithms, Java-specific discussion, or application code; those need different practice.

Start each task by stating what the method accepts and returns. Ask about nulls, empty inputs, duplicates, ordering, and whether you may mutate the input. A sensible contract is more useful than silently building a solution for a different problem.

Practice area Start here Follow-up to prepare
Strings Reverse, first unique, anagram What counts as a character?
Arrays Pair sum, second distinct maximum, deduplication Can input change or arithmetic overflow?
Fundamentals Prime check and numeric warm-ups Which values invalidate the shortcut?
References Reverse a linked list What happens to the remaining nodes?
Collections Merge records with duplicate keys Which value should survive?
Concurrency Update shared counts Is the whole operation atomic?

If explaining while typing is your main difficulty, use the separate live coding interview playbook alongside these Java-specific exercises. Keep the distinction clear: this session is about correctness in Java, while that guide helps you manage the conversation.

1. How would you reverse a string without hiding the logic?

Agree that this first version handles ASCII text and rejects null. Walk from the final index to zero, appending into a builder. For input 'trade', the result is 'edart'; empty input stays empty.

import java.util.Objects;

static String reverseAscii(String s) {
    Objects.requireNonNull(s);
    StringBuilder out = new StringBuilder(s.length());
    for (int i = s.length() - 1; i >= 0; i--) {
        out.append(s.charAt(i));
    }
    return out.toString();
}

Explain that the output requires O(n) space and the traversal takes O(n) time. Avoid repeatedly building an immutable string inside the loop, which can copy the accumulated prefix many times.

The useful follow-up is Unicode. Java string indices address UTF-16 code units, so this manual reversal can split a supplementary character. If the contract changes, reverse an array from s.codePoints().toArray() and append each value with appendCodePoint. Even code-point reversal doesn't preserve every user-perceived grapheme, such as a letter plus a combining mark. Define the required behavior instead of promising universal text reversal. Oracle's String documentation explains the representation.

2. How do you find the first non-repeating character?

First non-repeating character exercise checked on a printed input sheet

For ASCII input, count occurrences in one pass and scan the original string in a second pass. 'swiss' returns the index 1, pointing to 'w'; 'aabb' returns -1. Returning an index lets the caller distinguish no match from a valid character.

static int firstUniqueAscii(String s) {
    int[] counts = new int[128];
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c >= 128) throw new IllegalArgumentException("ASCII only");
        counts[c]++;
    }
    for (int i = 0; i < s.length(); i++) {
        if (counts[s.charAt(i)] == 1) return i;
    }
    return -1;
}

Test empty input, one character, repeated characters, and a unique final character. Null is rejected by the attempted string access; if the team's contract requires an explicit check, add one consistently.

The fixed alphabet makes additional space O(1), and two linear passes are still O(n). For unrestricted code points, use a frequency map and traverse the original code-point sequence again. Don't return the first key from a HashMap and assume it represents the earliest character: its iteration order isn't guaranteed. Oracle documents HashMap's ordering and performance assumptions.

On paper, mark repeated occurrences on a printed input sheet, then trace the second pass from the beginning. This exposes the common mistake of finding a unique value without preserving its original position.

3. How would you check whether two strings are anagrams?

Ask whether case, punctuation, and spaces matter. Under a lowercase English-letter contract, 'listen' and 'silent' match; 'aab' and 'abb' don't. Equal length alone cannot prove equal character counts.

Use an int[26]. Increment a position for each letter in the first string and decrement it for each letter in the second. Reject invalid characters explicitly, then require every count to be zero. The method takes O(n + m) time and constant extra space under that fixed alphabet.

If you sort character arrays instead, explain that it is an alternative with O(n log n + m log m) sorting time and space for the copies. Sorting is reasonable when clarity matters more than the linear-time target, but don't claim the costs are identical.

For the follow-up, normalize only according to the agreed rules. Removing punctuation silently could turn two different identifiers into a match. If text may include non-English characters, move beyond the 26-slot representation and discuss code points and normalization rather than increasing the array size at random.

4. How can you find two array indices whose values sum to a target?

Java two-sum interview exercise tested with one changing input

Return two distinct indices for one matching pair, or an empty array if none exists. For [4, 7, 4] and target 8, [0, 2] works. Check previously seen values before inserting the current one, so an element cannot match itself.

import java.util.HashMap;
import java.util.Map;

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

The long arithmetic prevents subtraction overflow from creating a false complement. The map stores long keys consistently, avoiding a lookup with one wrapper type and an insertion with another. Expected time is O(n) with well-distributed hashing; extra space is O(n).

Test [3, 3] with target 6, a single-element array, negatives, no solution, and values near integer limits. Say whether any valid pair is acceptable; if the interviewer requires a particular ordering among multiple answers, that changes the contract.

A common follow-up removes extra space. Sorting and two pointers can help, but original indices need tracking and in-place sorting mutates input. Explain those costs before swapping approaches. During a rehearsal, run this method in one editor and change only one failing input at a time so you can explain the failure precisely.

5. How do you find the second-largest distinct value?

Clarify 'distinct': [9, 9, 4] returns 4, while [9, 9] has no second distinct value. Using zero as the initial maximum fails for all-negative arrays; using Integer.MIN_VALUE as a missing marker collides with valid input.

import java.util.OptionalInt;

static OptionalInt secondDistinct(int[] values) {
    Integer largest = null;
    Integer second = null;
    for (int v : values) {
        if (largest == null || v > largest) {
            second = largest;
            largest = v;
        } else if (v < largest && (second == null || v > second)) {
            second = v;
        }
    }
    return second == null ? OptionalInt.empty() : OptionalInt.of(second);
}

The nullable local variables represent missing state, while OptionalInt makes absence explicit to the caller. The scan uses O(n) time and O(1) extra space. Check empty input, one distinct value, repeated maxima, negative values, and [0, Integer.MIN_VALUE].

If asked for the kth largest, explain when a heap or selection algorithm becomes worthwhile. Don't generalize two carefully tracked variables into dozens of special cases.

6. How do you remove duplicates from a sorted array in place?

The sorted-input contract lets you compare each new value with the last retained value. Keep a write index and return the length of the valid prefix; the remaining tail has no promised meaning.

static int deduplicateSorted(int[] values) {
    if (values.length == 0) return 0;
    int write = 1;
    for (int read = 1; read < values.length; read++) {
        if (values[read] != values[write - 1]) {
            values[write++] = values[read];
        }
    }
    return write;
}

For [2, 2, 5, 5, 8], return 3 and inspect only the prefix [2, 5, 8]. A test expecting the array itself to shrink misunderstands the API. The algorithm is O(n) time and O(1) extra space.

If input becomes unsorted and first-seen order matters, consider LinkedHashSet with extra memory. A TreeSet would sort the result and change the time cost; a HashSet would not promise the same encounter order. Name the behavior the caller needs before choosing the collection.

7. How do you test whether an integer is prime?

Return false below 2, then look for a divisor no larger than the square root. Use d <= n / d instead of d * d <= n so the loop condition cannot overflow an int as d grows.

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

Explain why checking past the square root is unnecessary: a factor pair with both factors larger than that would exceed n. Time is O(sqrt(n)); extra space is O(1). Test -3, 0, 1, 2, 9, and 49, including the boundary where the divisor equals the square root.

Use other numeric programs as warm-ups, with explicit boundaries. For parity, n % 2 != 0 handles negative odd numbers. For factorial, agree that 0! equals 1 and discuss overflow before accepting large inputs. For Fibonacci, state whether the sequence starts at 0 and 1 and whether the request means an index or a count. For digit reversal and numeric palindromes, define negative-number behavior and check the result range. Armstrong-number exercises need a digit-count-based exponent, rather than cubing every digit regardless of input length.

8. How would you reverse a singly linked list?

Keep previous, current, and next references. Save next before redirecting current.next, or you lose access to the unprocessed chain. Starting with A pointing to B pointing to C, finish with C pointing to B pointing to A and return C.

static final class Node {
    final int value;
    Node next;
    Node(int value) { this.value = value; }
}

static Node reverse(Node head) {
    Node previous = null;
    Node current = head;
    while (current != null) {
        Node next = current.next;
        current.next = previous;
        previous = current;
        current = next;
    }
    return previous;
}

This assumes an acyclic list that you may mutate. It uses O(n) time and O(1) extra space. Test null, one node, and several nodes; also verify that the former head now has a null next reference.

If other code holds references into the list, mutation affects what that code observes. Discuss copying when preservation is required. A recursive version uses call-stack space and can run out of stack on a long list, so explain the trade-off rather than calling both versions constant-space.

For the wider design conversation about ownership and mutable objects, the object-oriented design interview guide gives you a separate worked example.

9. How should a stream handle duplicate keys?

Suppose you receive records containing an ID and a score, and must retain the highest score for each ID. Define null handling and score type first. With non-null records, non-null String IDs, and int scores, collect using Collectors.toMap(Score::id, Score::value, Integer::max). Score here represents your own class exposing id() and value() methods, not a built-in Java type.

Explain the merge function: if the same key arrives twice, the larger score survives. Without a merge rule, the two-argument toMap collector throws for duplicate mapped keys. If encounter order matters in the output, supply a LinkedHashMap factory through the four-argument overload. Oracle's Collectors reference documents these overloads.

Test two different IDs, repeated IDs with higher and lower scores, ties, and an empty source. Compare the stream with a loop using map.merge(id, score, Integer::max). Choose whichever you can explain and debug clearly; a shorter expression doesn't excuse an undefined duplicate policy.

10. What goes wrong when two threads update a shared count?

The expression map.put(key, map.getOrDefault(key, 0) + 1) contains a read and a write. Two threads can read the same count and both write the same incremented value, losing one update. Replacing HashMap with ConcurrentHashMap doesn't make this compound expression atomic.

For per-key integer counts, one option is ConcurrentHashMap<String, Integer> counts followed by counts.merge(key, 1, Integer::sum). State that this protects the per-key update, not an arbitrary multi-key invariant or a complete snapshot across all keys. Also consider overflow if counts can exceed the integer range.

Use a small execution trace in your answer: both threads read 4, then both write 5, when the intended result was 6. A passing stress test cannot prove a race is absent. For a live interview, this explanation is often more useful than immediately introducing a more elaborate counter design. The ConcurrentHashMap API is the reference for its operation guarantees.

How can you turn these questions into a useful mock interview?

Candidate considering a changed requirement during a Java mock interview

Ask a practice partner to choose one string task and one array task without showing you the selection beforehand. Give them a printed input sheet and ask them to change a requirement after your first working solution. A normal quiet room is enough; the useful pressure comes from explaining a decision to another person.

Use this suggested 45-minute session:

  1. Spend five minutes clarifying contracts and selecting representative tests.
  2. Spend twenty minutes solving the two tasks and checking the code.
  3. Spend ten minutes handling one changed requirement and one Java-specific follow-up.
  4. Spend ten minutes reviewing mistakes and redoing the failing case without hints.

Score contract clarity, correctness, test quality, and explanation from zero to two each. Zero means missing, one means partial or prompted, and two means independent and accurate. This is a personal practice tool, not an employer's scoring system. Keep the failing input and one sentence describing the mistaken assumption, then revisit that exact case in your next session.

If you'd like spoken practice support, Hiintly can transcribe a rehearsal and suggest answers while you work through a coding question. Its free 10-minute session becomes available again after a five-minute cooldown. Use suggestions to challenge your explanation, then close them and solve the problem independently. During a real assessment, follow the employer's rules for outside assistance and ask when the policy is unclear.

Your next practice session should end with a solution you can explain from its input contract to its failure cases. Pick the weakest task from the mock, change one boundary condition, and check whether the reasoning still holds.

Frequently Asked Questions

Which Java coding questions should a fresher practise?
Start with string traversal, frequency counting, array scans, and simple number problems. Practise stating the input contract, writing a correct solution, and testing empty inputs, duplicates, and boundary values before moving to concurrency.
Should I use streams in a Java coding interview?
Use streams when they express the task clearly and the environment supports them. Be ready to explain duplicate keys, ordering, and the equivalent loop. A stream expression is not automatically clearer or more efficient.
Can I use built-in collection methods?
Ask whether the interviewer wants the underlying algorithm or an application-level solution. If built-ins are permitted, explain their behavior and costs. If they are excluded, implement the requested logic directly.
How do I prepare for Java coding questions with experience?
Keep the basic algorithms sharp, then practise changed requirements involving ordering, overflow, mutation, duplicate keys, and atomic updates. Explain which guarantee each library operation provides and where that guarantee ends.
How many Java questions should I solve before an interview?
Use independent performance rather than a fixed total. You should be able to solve representative tasks, test them, explain their complexity, and adapt to a follow-up without recalling a memorized answer.
What should I do if my Java solution fails during the interview?
State the failing input and expected output, trace the smallest relevant part of the code, and explain the assumption you are checking. Fix one issue at a time and rerun the original failure before adding another case.

Ready To Ace Your Next Interview?

Get undetectable support and personalized guidance to ace live interviews with confidence.