Interview questions

Java Developer Interview Questions with Answers

This guide helps you explain your decisions and discuss trade-offs in a Java interview. A question's level is a guide to the depth of the conversation; the requirements of a particular team are set by the job posting.

Get Offer editorial team · Reviewed

Java 21. The description of @Transactional refers to the proxy mode of Spring Framework 6.2; the SQL task checks transaction semantics separately from Spring.

Questions and answers

Junior: fundamentals

Objects

How are equals and hashCode related?

equals defines logical equality, and hashCode helps a hash collection choose where to look. Equal objects must have equal hashes; the reverse is not true: the same hash does not yet mean equality. When you override equals, you usually need to override hashCode consistently. The fields used in both methods must reflect the same identity. Symmetry, transitivity and consistency of equality matter for predictable collection behavior.

Example
Two user objects with the same immutable ID can be considered equal regardless of the name.
Common mistake
Overriding equals and leaving an incompatible hashCode.
Interviewer follow-up
What breaks if you change a key field after putting the object into a HashMap?
Parameters

Does Java pass objects by reference?

Java passes arguments by value. For an object, that value is a reference. The method gets a copy of the reference and can change the object it points to, but reassigning the parameter does not replace the caller's variable. This answer resolves the apparent contradiction between modifying a list inside a method and being unable to write an ordinary swap of two outside references. Immutable objects further limit the changes that can be observed through a shared reference.

Example
Adding to a passed ArrayList is visible to the caller; assigning a new ArrayList to the parameter is not.
Common mistake
Saying “everything is passed by reference” without distinguishing the object from the variable.
Interviewer follow-up
Why does swapping the values of two parameters not change the caller's variables?
Strings

Why is String immutable?

Once a string is created, its sequence of characters cannot be changed. Transformation operations return a result instead of editing the original object. This makes sharing strings predictable and lets you safely use a string as a key. However, frequent concatenation in a loop can create intermediate results; StringBuilder helps when building a large text. String immutability does not make the container that holds a reference to the string thread-safe.

Example
s.toUpperCase() does not change s if the result is not assigned anywhere.
Common mistake
Comparing String contents with ==.
Interviewer follow-up
When is StringBuilder more appropriate than concatenating a few constants?
Collections

How do you choose between List, Set and Map?

List stores a sequence and allows duplicates, Set represents unique elements, and Map associates keys with values. Then you choose a specific implementation by iteration order, operations and concurrency requirements. You cannot infer a guaranteed HashMap order from how it looks in one run. TreeMap requires a consistent comparison of keys, and LinkedHashMap preserves a defined order. The interface contract matters more than a habit of always using one class.

Example
LinkedHashSet fits an ordered set of unique visited URLs.
Common mistake
Choosing a structure only by its average lookup complexity and forgetting about order and updates.
Interviewer follow-up
How does the elements' equals differ from a Comparator in a sorted collection?
Performance

How is ArrayList different from LinkedList?

ArrayList stores elements in an array and gives fast access by index; inserting in the middle requires a shift. LinkedList consists of nodes, but finding the right index requires a traversal. So the claim “inserting into a LinkedList is always faster” is wrong unless the position has already been found. In practice, extra objects, memory and data locality matter too. For a double-ended queue, ArrayDeque is often more appropriate.

Example
If a task constantly reads elements by index, LinkedList usually does not match its main operations.
Common mistake
Comparing only the cost of updating references while ignoring the search for the position.
Interviewer follow-up
How do you measure collection behavior under a real workload?
Exceptions

How is a checked exception different from an unchecked one?

A checked exception must be handled or declared in the signature; unchecked subclasses of RuntimeException have no such compiler requirement. This distinction says nothing about how serious an error is or whether it can be ignored. The API contract should explain what the caller can do on failure. When converting an error, keep the cause. A broad catch with an empty body turns a clear failure into corrupted state or a false successful result.

Example
A file read error can be part of the expected contract, while an invalid index is an error in how the API is used.
Common mistake
Treating every RuntimeException as unrecoverable and every checked exception as safe.
Interviewer follow-up
Where is the best place to convert an infrastructure error into a domain error?
Resources

What is try-with-resources for?

The construct automatically closes resources that implement AutoCloseable when the scope is left. Several resources are closed in reverse order. If an error occurs both during the work and on closing, the additional error may end up suppressed, so when diagnosing you cannot look only at the short message. Managing a resource does not replace understanding the transaction: a closed connection and successfully committed changes are different facts.

Example
A file input stream must be closed even when parsing its contents fails.
Common mistake
Relying on the garbage collector to close files and connections in time.
Interviewer follow-up
How do you get the exceptions suppressed during closing?
Testing

What makes a unit test useful?

A test pins down an observable contract with a clear example. It must tell correct behavior apart from a likely wrong implementation. Check the result, the side effects and the specific type of failure if it is part of the contract. Overly strict checks of the order of internal calls get in the way of safe refactoring. For time, the network and randomness, controlled dependencies help. One large test with many unrelated assertions makes it hard to understand why it failed.

Example
A key equality test should also show a successful HashMap lookup with another, equal instance.
Common mistake
Mocking the very logic under test and asserting that the mock returned the configured result.
Interviewer follow-up
What check is needed in addition to a repository unit test?

Middle: putting them into practice

Typing

What does PECS mean for generics?

The Producer Extends, Consumer Super rule helps you choose wildcard bounds. If a structure only hands out values as T, ? extends T often fits; if it accepts T, ? super T is useful. This does not make arbitrary writes safe: from a list of an unknown subtype you cannot conclude that it accepts any base type. For a structure that both reads and writes one specific type, a plain T parameter without a wildcard may be needed.

Example
You can read Number from a List<? extends Number>, but you cannot add an arbitrary Integer to it.
Common mistake
Treating List<Integer> as a subtype of List<Number>.
Interviewer follow-up
How do you write the signature of a method that copies elements between two lists?
Collections

Why is a mutable key dangerous for a HashMap?

When adding an entry, HashMap uses the key's hash and its equality. If you then change a field used in hashCode or equals, a lookup may go to a different area than where the entry originally landed. The object physically remains in the collection, but a plain get may not find it. It is more reliable to use an immutable ID or an immutable value object. Changing other fields is acceptable only if it does not affect the identity contract.

Example
A key with an email field loses the expected behavior after the email changes if hashCode is computed from it.
Common mistake
Expecting HashMap to rebuild its index automatically after a key changes.
Interviewer follow-up
Which restrictions of record help you follow the rules for keys?
Data processing

How is a Stream different from a collection?

A collection stores elements, while a Stream describes the processing of a source. Intermediate operations are usually lazy, and a terminal operation starts the computation. A Stream is not meant to be reused after a terminal operation. Transformation functions should preferably have no dependent side effects: this matters especially for parallel execution. parallelStream does not guarantee a speedup and requires you to consider the source, the volume, the cost of the operation and contention for the common pool.

Example
filter(...).map(...) without a terminal operation has not produced a result list yet.
Common mistake
Modifying a shared ArrayList from a parallel forEach.
Interviewer follow-up
When is a plain loop clearer than a pipeline?
JVM

What lives on the heap and on the stack?

Each thread has a call stack with frames of the methods being executed; objects are usually considered to be allocated on the shared heap. The JIT, however, can optimize allocation and even eliminate the creation of some objects, so the language description should not be confused with a specific machine representation. A memory leak is possible in Java when unneeded objects remain reachable. The garbage collector frees what is unreachable, but it does not know which cache entries the business no longer needs.

Example
An unbounded map with references to old results keeps them alive even while the GC is working.
Common mistake
Claiming that having a GC rules out memory leaks entirely.
Interviewer follow-up
What data helps you tell a leak from a short-term spike in load?
Multithreading

What does volatile guarantee?

volatile sets rules for the visibility and ordering of access to a variable, but it does not turn a compound operation into an atomic one. The expression counter++ involves a read, a computation and a write, so two threads can lose an update. For a counter, use a suitable atomic operation, and for an invariant across several fields, shared synchronization. Choose the tool by the state it protects, not by the principle “let's add volatile to every field”.

Example
A stop flag can be read through volatile; updating a related pair of balances needs a stronger mechanism.
Common mistake
Mistaking visibility for atomicity of a read-modify-write operation.
Interviewer follow-up
When will AtomicInteger not solve the problem of state correctness?
Multithreading

What does synchronized protect?

A monitor provides mutual exclusion for threads that use the same monitor, along with the necessary visibility guarantees. If reads are guarded by one lock and writes by another, there is no shared critical section. Long network operations inside a lock make the other threads wait longer. With several locks, you need a consistent acquisition order, otherwise a deadlock is possible. The keyword itself does not choose the correct boundary of a business operation.

Example
Checking the balance and debiting it must be protected together if they form a single invariant.
Common mistake
Synchronizing only the writes and reading mutable state without a consistent mechanism.
Interviewer follow-up
How do you detect and reproduce a deadlock?
Asynchrony

How is thenApply different from thenCompose?

thenApply transforms a successful result with a function. If the function returns another CompletionStage, you get a nested structure; thenCompose flattens such a sequential asynchronous dependency. Independent results can be combined with thenCombine. You also need to choose an executor for heavy work, the behavior on error and an overall timeout. A method name ending in Async does not guarantee that a blocking call has become cheap or safe for the common pool.

Example
Loading a user and then their settings is a sequence; loading two independent lookup tables is a combination.
Common mistake
Calling join right after each launch and so waiting for independent operations one by one.
Interviewer follow-up
How do you return a fallback result only for a specific kind of error?
Spring

How does dependency injection help testing?

An object receives its dependencies from outside, so creating them is separated from the business logic. A constructor makes the required dependencies explicit and lets you assemble the service in a test without the full application. The Spring container manages creating and wiring objects, but it does not remove the need for clear boundaries. Too many dependencies in a service can indicate mixed responsibilities. Not every unit test needs a Spring context.

Example
An order service can be tested with a controlled repository and a clock passed to the constructor.
Common mistake
Reaching into a global container inside every method instead of having an explicit contract.
Interviewer follow-up
When do you need an integration test with a Spring context?

Senior: trade-offs and reliability

Spring and databases

Why might @Transactional not work?

In Spring's usual proxy mode, transactional interception happens when the call goes through the proxy. An internal call to a method of the same object can bypass this mechanism. The chosen transaction manager, the operation boundary and the rollback rules also matter. By default, in a common configuration, runtime errors lead to a rollback, but the behavior for checked exceptions must be set and verified explicitly. State the Spring version and the configuration mode: the annotation is not universal magic around any call.

Example
If an outside service calls a transactional method through a managed bean, interception is possible; this.save() inside the same object takes a different path.
Common mistake
Assuming that the presence of the annotation by itself proves a transaction was opened.
Interviewer follow-up
How do you test a rollback against a real test database?
Multithreading

When are Java 21 virtual threads useful?

Virtual threads lower the cost of a large number of concurrently waiting tasks and let you keep the sequential style of blocking code. They do not increase CPU performance and do not lift the limits of an external resource. If the database allows dozens of connections, thousands of waiting tasks still have to respect that limit. For Java 21, separately check the places where a blocking operation pins the carrier thread, and how libraries behave. Confirm the decision with a load test.

Example
Many independent requests with I/O can benefit from cheap waiting, but hashing a large file needs CPU.
Common mistake
Treating a virtual thread as free, with no limits on memory, connections and queues.
Interviewer follow-up
How do you limit the load on an external service when there are many threads?
Consistency

How do you protect against concurrent data updates?

The choice depends on the invariant and on how often conflicts happen. The optimistic approach checks the record version and, on a conflict, offers a retry or a rejection. A pessimistic lock serializes access but requires short transactions and control over the acquisition order. A unique index protects constraints better than a separate pre-check in code. A transaction retry must account for external effects that have already happened: an email or a payment cannot be retried automatically together with the database query.

Example
Two requests to book the last seat must not both succeed just because each of them first read a remaining count of 1.
Common mistake
Solving a race between processes with synchronized in a single application instance.
Interviewer follow-up
When is an UPDATE with a condition enough, and when do you need a row lock?
Diagnostics

How do you investigate growing latency in a JVM service?

First compare throughput, the latency distribution, errors and queues with a normal period. Then check GC pauses, heap usage, CPU load, thread states and waiting for external services. Increasing the heap may hide the symptom but will not remove the retention of unneeded objects. The average response time hides rare long operations, so you need percentiles and correlation with specific requests. Verify changes under a comparable load.

Example
A growing connection pool queue explains latency even when the application's CPU usage is low.
Common mistake
Tuning GC parameters at random without a profile and a reproducible scenario.
Interviewer follow-up
What signs tell blocked threads apart from a lack of CPU?

Practical tasks

1. An immutable HashMap key

Create an account key from tenant and id. Two equal keys must find the same entry.

Expected result. A lookup with a new key holding the same values returns the stored name.

Solution and explanation

A record automatically generates equals and hashCode from its components. In this example, the String and long components hold no mutable user state.

java
import java.util.HashMap;

class KeyExample {
    record AccountKey(String tenant, long id) {}
    public static void main(String[] args) {
        var values = new HashMap<AccountKey, String>();
        values.put(new AccountKey("team", 7), "Alice");
        if (!"Alice".equals(values.get(new AccountKey("team", 7))))
            throw new AssertionError("equal key not found");
        if (values.containsKey(new AccountKey("other", 7)))
            throw new AssertionError("different tenant matched");
    }
}

2. Combine independent results

Combine two successful asynchronous operations by adding their results. If one of them fails, do not return a successful sum.

Expected result. 20 and 22 give 42; a failed operation leads to exceptional completion.

Solution and explanation

thenCombine builds a dependency on both results. In the example, completedFuture makes the check deterministic; the actual launch and the executor are chosen separately.

java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

class FutureExample {
    public static void main(String[] args) {
        var a = CompletableFuture.completedFuture(20);
        var b = CompletableFuture.completedFuture(22);
        if (a.thenCombine(b, Integer::sum).join() != 42)
            throw new AssertionError("wrong sum");
        var failed = CompletableFuture.<Integer>failedFuture(new IllegalStateException("unavailable"));
        try {
            a.thenCombine(failed, Integer::sum).join();
            throw new AssertionError("failure disappeared");
        } catch (CompletionException expected) {
            if (!(expected.getCause() instanceof IllegalStateException)) throw expected;
        }
    }
}

3. Check a transactional rollback

In a test database, perform a debit and a credit in one transaction. Raise an error between them. Check the state through a new connection.

Expected result. Both original balances are preserved; there is no partial debit.

Solution and explanation

The operations are combined in one transaction, and on error a rollback is performed. For Spring, you additionally need an integration test through a managed bean with @Transactional, not a directly instantiated class. The SQL below illustrates the transaction boundary itself, not Spring settings.

sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER NOT NULL);
INSERT INTO accounts VALUES (1, 100), (2, 50);
BEGIN;
UPDATE accounts SET balance = balance - 20 WHERE id = 1;
-- Simulate a failure before the credit and roll back:
ROLLBACK;
SELECT id, balance FROM accounts ORDER BY id;
-- Expected: (1, 100), (2, 50).

Seven-day preparation plan

  1. Write down the job requirements and mark the topics you know and the ones you don't.
  2. Answer the Junior questions out loud, then check yourself against the explanations.
  3. Work through the Middle questions. For every mistake, write a small example of your own.
  4. Solve the practical tasks without hints and check the edge cases.
  5. Work through the Senior questions and explain the trade-offs as they apply to your project.
  6. Run a mock interview: clarify the conditions, reason out loud and check your conclusions.
  7. Go over your mistakes, prepare real stories from your experience and check your equipment.

Sources to check and keep learning from