Senior Java Interview Questions: What Interviewers Are Really Testing
- #Java
- #Interviews
- #Career
- #senior-engineer
Most lists of senior Java interview questions have the same flaw. They give you a hundred questions and a one-line answer for each, so you prepare by memorising definitions. Then the interviewer asks "and what happens if that key changes after you insert it?" and the definition runs out.
At senior level, the question is usually just the way in. A good interviewer wants to see whether you understand the mechanism, whether you know how it fails in production, and whether you can say when you'd choose something else.
So this list is short on purpose: 20 questions, grouped by the area they probe. For each one you get what a weak answer sounds like, what a strong one sounds like, and the signal behind it. Every code example and output below was run on Java 25 (Corretto 25.0.4.1).
How to tell a weak answer from a strong one
Almost every answer lands on one of three levels:
- The definition. "
volatilemakes a variable visible to all threads." True, and enough for a junior role. - The mechanism. You can explain why it works: the write happens-before later reads of that variable.
- The consequence. You know where it stops working:
volatiledoesn't makecount++atomic, so here's what you'd use instead and what it costs.
Senior interviews are looking for the third level. If you're stuck on a question, moving one level down that list is usually the best thing you can do out loud.
Language depth
1. What's the contract between equals and hashCode?
Weak answer: "If you override one, override the other."
Strong answer: Equal objects must have equal hash codes. Unequal objects may collide. Break the rule and hash-based collections look in the wrong bucket, so an object that is "equal" can't be found:
final class Money {
final String currency;
final long cents;
Money(String currency, long cents) {
this.currency = currency;
this.cents = cents;
}
@Override
public boolean equals(Object o) {
return o instanceof Money m
&& m.cents == cents
&& m.currency.equals(currency);
}
// no hashCode
}
Set<Money> set = new HashSet<>();
set.add(new Money("BRL", 100));
new Money("BRL", 100).equals(new Money("BRL", 100)); // true
set.contains(new Money("BRL", 100)); // false
A strong candidate then brings up the follow-up on their own: if a field used
in hashCode changes while the object is in a HashMap, the entry is
effectively lost.
The real signal: whether you've thought about how your objects behave inside the structures that hold them. JPA entities are the classic place this goes wrong, because the ID is often null until the entity is saved.
2. How do you make a class immutable?
Weak answer: "Make the fields final," or "use a record."
Strong answer: final protects the reference, not what it points to. A
record holding a mutable list is only shallowly immutable:
record Team(String name, List<String> members) {}
List<String> names = new ArrayList<>(List.of("Ana"));
Team team = new Team("core", names);
names.add("Bruno");
team.members(); // [Ana, Bruno]
The fix is a defensive copy in the compact constructor:
record SafeTeam(String name, List<String> members) {
SafeTeam {
members = List.copyOf(members);
}
}
The real signal: whether you know the difference between a guarantee and a convention.
3. What is type erasure, and what does it stop you doing?
Weak answer: "Generics are removed at compile time."
Strong answer: At runtime, ArrayList<String> and ArrayList<Integer>
are the same class. That's why you can't write new T() or ask an arbitrary
Object whether it's a List<String>. It also explains why a raw cast can
put an Integer in a List<String>, with the ClassCastException appearing
later, at the line that reads it, far from the actual bug. The best answers
add that erasure isn't total: generic signatures on fields, methods and
superclasses stay in the class file, which is how Jackson's TypeReference
and Spring's ResolvableType work.
The real signal: whether you can debug a failure that shows up far from its cause.
4. When do you use ? extends and when ? super?
Weak answer: Reciting "PECS" with no example.
Strong answer: Use extends when you read from a collection and super
when you write to it:
static double sum(Collection<? extends Number> source) {
double total = 0;
for (Number n : source) total += n.doubleValue();
return total;
}
static void addOneToThree(Collection<? super Integer> sink) {
sink.add(1);
sink.add(2);
sink.add(3);
}
sum accepts a List<Integer> or a List<Double>. addOneToThree accepts a
List<Integer>, List<Number> or List<Object>.
The real signal: whether you can design an API other people will call. If you want a refresher, the collections and generics post covers the basics.
The JVM
5. Where do objects and local variables live?
Weak answer: "Objects on the heap, primitives on the stack."
Strong answer: Local variables live in the stack frame, and that includes references. The objects they point to live on the heap, and so do primitive fields of those objects. Then the useful nuance: if the JIT proves an object doesn't escape a method, escape analysis can remove the allocation through scalar replacement.
The real signal: whether your mental model is accurate enough to reason about allocation pressure.
6. Which garbage collector does your service run, and why?
Weak answer: "G1, it's the default."
Strong answer: G1 is the default on most server machines, but the JVM chooses based on the environment. On JDK 25 with one available CPU it picks Serial, which catches teams running small containers by surprise. You can check rather than guess:
java -XX:ActiveProcessorCount=1 -XX:+PrintFlagsFinal -version | grep -E 'UseSerialGC|UseG1GC'
From there, the choice is a trade-off: G1 for balanced throughput and pauses, ZGC when tail latency matters most and you can spend more CPU and memory, Parallel for batch jobs that care about throughput. Knowing that ZGC is generational-only since JDK 24 is a nice sign you're current.
The real signal: whether you've looked at how your software actually runs or assumed the defaults fit.
7. A service dies with OutOfMemoryError. What do you do?
Weak answer: "Increase -Xmx."
Strong answer: First read which memory ran out, because Java heap space,
Metaspace, Direct buffer memory and unable to create native thread are
four different problems. For the heap, capture a dump
(-XX:+HeapDumpOnOutOfMemoryError) and look at what's retaining memory in a
tool like Eclipse MAT. If the container was OOM-killed with no Java error at
all, the heap may be fine and the growth is in native memory, which is what
Native Memory Tracking (-XX:NativeMemoryTracking=summary with jcmd) is for.
The real signal: whether you diagnose before you change things.
Collections
8. How does HashMap work inside?
Weak answer: "It stores key-value pairs using a hash."
Strong answer: The key's hash is spread (h ^ (h >>> 16)) and masked to
pick a bucket. Collisions chain in the bucket. The table starts at 16 and
doubles when size passes capacity × 0.75. Since Java 8, a bucket with more
than 8 entries becomes a red-black tree, but only once the table has at least
64 slots. Below that, the map resizes instead.
The real signal: whether you know why it's O(1) on average, and what makes it degrade.
9. ArrayList or LinkedList?
Weak answer: "LinkedList is faster for inserts."
Strong answer: Only once you already hold the node, and getting there is
O(n). Each node is also a separate object scattered across the heap, so
iteration loses the CPU cache benefit an array gets. In practice, ArrayList
is the default, and ArrayDeque is what you want for a queue or stack.
The real signal: whether you think past Big-O to how memory behaves.
10. What causes ConcurrentModificationException?
Weak answer: "Two threads changing a list."
Strong answer: It doesn't need two threads. Removing inside a for-each on the same thread is enough. And detection is best-effort, which is the part most candidates miss. Remove the second-to-last element and the loop exits early with no exception, having skipped the last element:
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4));
for (Integer i : list) {
if (i == 3) list.remove(i);
}
// no exception, and 4 was never visited
// list is [1, 2, 4]
Use removeIf instead.
The real signal: whether you know a missing exception doesn't prove the code is right.
11. ConcurrentHashMap or Collections.synchronizedMap?
Weak answer: "ConcurrentHashMap is faster."
Strong answer: It scales better under contention, but the bigger point is
that neither one makes your compound operations atomic. With eight threads
each incrementing a key 100,000 times, a get-then-put on a synchronized map
finished at 228,800 in one run instead of 800,000. merge got it exactly
right:
counts.merge(key, 1, Integer::sum);
Also worth saying: ConcurrentHashMap rejects null keys and values, so code
migrated from HashMap can start throwing.
The real signal: whether you see that a thread-safe class doesn't make the code around it thread-safe.
Concurrency
12. Why isn't count++ thread-safe? Does volatile fix it?
Weak answer: "Add volatile."
Strong answer: count++ is a read, an add and a write, and two threads can
interleave between those steps. volatile guarantees visibility, not
atomicity. With eight threads adding a million each, a plain counter ended at
6,654,894 instead of 8,000,000 in one run, while AtomicInteger was exact.
Under heavy contention, LongAdder is often the better fit for a metric.
The real signal: whether you separate visibility from atomicity, which is the base of everything else in concurrency.
13. What does happens-before mean?
Weak answer: "One thing runs before another."
Strong answer: It's the Java Memory Model's rule for when a write is
guaranteed visible to a read. Without that relationship, the compiler and CPU
may reorder things, and another thread may see stale values. Unlocking
happens-before a later lock of the same monitor, a volatile write
happens-before later reads of it, and Thread.start and join create edges
too. The classic example is double-checked locking, which needs volatile
on the instance field, or another thread can see a reference to an object
whose constructor effects aren't visible yet.
The real signal: whether you reason from guarantees or from "it worked on my machine".
14. synchronized or ReentrantLock?
Weak answer: "ReentrantLock is more modern."
Strong answer: Use synchronized until you need something it can't do:
tryLock, a timeout, interruptible waits, fairness, or several conditions on
one lock. The old advice to replace synchronized so virtual threads wouldn't
pin is out of date. Since JDK 24 (JEP 491), a virtual thread blocking inside
synchronized releases its carrier. On Java 25 with a single carrier thread,
200 virtual threads each sleeping 500 ms inside synchronized finished in
about 501 ms.
The real signal: whether your knowledge moved along with the platform.
15. How do exceptions and threads work in CompletableFuture?
Weak answer: "It runs things asynchronously."
Strong answer: Three things. A failure skips the dependent stages and
surfaces wrapped: join() throws CompletionException, get() throws
ExecutionException, and the original is in getCause(). thenApply with a
function that returns a future gives you a nested future, so you want
thenCompose. And the *Async methods default to the common ForkJoinPool,
sized for CPU work, so blocking I/O there can starve everything else in the
JVM using it. Pass your own executor.
The real signal: whether you know where your code is actually running.
Streams
16. When does a stream actually execute?
Weak answer: "When you call it."
Strong answer: Intermediate operations are lazy. Nothing runs until a
terminal operation, and short-circuiting ones stop early. For
Stream.of(1, 2, 3, 4).filter(isEven).findFirst(), the filter runs on 1 and 2
and never sees 3 or 4. This is also why side effects in peek or map are a
bad idea: whether they run depends on the rest of the pipeline.
The real signal: whether you treat a stream as a pipeline description rather than a loop.
17. What can go wrong with Collectors.toMap?
Weak answer: "Nothing, it builds a map."
Strong answer: Two production failures. A duplicate key throws
IllegalStateException, and a null value throws NullPointerException. The
first is the one that passes tests and breaks on real data:
record User(String email, String name) {}
Stream.of(new User("[email protected]", "Ana"), new User("[email protected]", "Ana B"))
.collect(Collectors.toMap(User::email, User::name));
// IllegalStateException: Duplicate key [email protected]
// (attempted merging values Ana and Ana B)
Stream.of(new User("[email protected]", "Ana"), new User("[email protected]", "Ana B"))
.collect(Collectors.toMap(User::email, User::name,
(first, second) -> second));
// {[email protected]=Ana B}
A strong candidate also notes that the merge function is a business decision: which record wins?
The real signal: whether you think about the data you'll get rather than the data you expect.
18. When should you use a parallel stream?
Weak answer: "When you want it to go faster."
Strong answer: Rarely, and only for CPU-bound work on large, easily split
data with no shared mutable state, after measuring. It runs on the common pool
by default, so it's a poor fit for blocking calls in a web service. Shared
state is the worst trap: forEach(list::add) into an ArrayList from a
parallel stream of 100,000 elements left 15,402 elements in one run, with
no exception. Use a collector.
The real signal: whether you default to measuring instead of assuming.
Modern Java
19. What do records and sealed types give you together?
Weak answer: "Less boilerplate."
Strong answer: Together they model a closed set of cases, and the compiler checks you handled all of them:
sealed interface Payment permits Card, Pix, Boleto {}
record Card(String last4) implements Payment {}
record Pix(String key) implements Payment {}
record Boleto(String barcode) implements Payment {}
static String describe(Payment p) {
return switch (p) {
case Card c -> "card ending " + c.last4();
case Pix x -> "pix to " + x.key();
case Boleto b -> "boleto " + b.barcode();
};
}
There's no default, on purpose. Add a new payment type and this stops
compiling until you handle it, which turns a runtime bug into a build error.
The real signal: whether you use the type system to make bad states hard to reach.
20. When do virtual threads help, and when don't they?
Weak answer: "They make Java faster."
Strong answer: They raise throughput for blocking work by making a
waiting thread cheap. Ten thousand tasks each sleeping one second finished in
about 1.04 s on a single carrier thread. They do nothing for CPU-bound work.
Don't pool them, since they're meant to be created per task. And removing the
thread limit can move the bottleneck: if nothing else caps concurrency, ten
thousand requests can hit a database pool of twenty. A Semaphore is the
usual way to limit access to a scarce resource.
The real signal: whether you can adopt a new feature and also see what it shifts elsewhere in the system.
How to prepare with this list
Don't memorise the answers. For each question, try to do three things without looking: explain the mechanism, name one way it fails, and write a few lines that show it. If you can't produce the failure, run it. Most examples here fit in a single file, and watching a counter come up short will stay with you longer than reading about it.
Then connect them to your own work. "I know ConcurrentHashMap" is weaker than
a real story about a race you found and fixed, and the
STAR method is a good way to structure
it. The Java round is also only one part of the loop, so read
how to prepare for the senior or staff engineer interview
for the system design and past-project rounds. If the role is Spring-heavy,
Spring Boot Interview Questions covers
the framework round.
If you don't know something in the interview, say so and reason from what you do know. "I haven't used that, but given how X works I'd expect Y" is a strong senior answer. A confident guess that falls apart on the follow-up is not.