ExtraBrain Interview Questions

Java Interview Questions for 2026, With Tested Answers

Short answer

Java interviews in 2026 mix classic core questions with features from Java 17 to 25. Expect the equals and hashCode contract, how HashMap behaves, fail-fast iteration, records, sealed interfaces with pattern-matching switch, and virtual threads, including when they don't help and what still pins a carrier thread. Answer with the rule, a short example and the bug it prevents.

Java interview questions for 2026: equals and hashCode, HashMap, records, sealed types, pattern matching and virtual threads, with code tested on JDK 25.

  • Java
  • Coding Interviews
  • Technical Interviews

Java interviews have a long memory. You will still get the equals and hashCode question that has been asked for twenty years, and in the same loop someone will ask whether virtual threads mean you can delete your thread pools. The language has moved a lot since Java 17, and interviewers at companies running JDK 25, the current long-term support release from most vendors, expect you to know the newer features.

Every program below compiles with javac --release 25 and was run on a current JDK.

Core language questions

What is the contract between equals and hashCode?

The Object documentation states it: if two objects are equal according to equals, calling hashCode on each must produce the same integer. Unequal objects may share a hash code, though distinct codes help hash table performance. Break the rule and hash-based collections stop finding your objects:

import java.util.HashSet;
import java.util.Set;
public class EqualsHashCode {
static final class Email {
private final String address;
Email(String address) {
this.address = address;
}
@Override
public boolean equals(Object o) {
return o instanceof Email other && address.equalsIgnoreCase(other.address);
}
// hashCode() is missing, so equal objects get unrelated hash codes
}
record EmailRecord(String address) {
EmailRecord {
address = address.toLowerCase(); // normalize once, in the compact constructor
}
}
public static void main(String[] args) {
Set<Email> broken = new HashSet<>();
broken.add(new Email("Ada@example.com"));
System.out.println(broken.contains(new Email("ada@example.com"))); // false in practice
Set<EmailRecord> fixed = new HashSet<>();
fixed.add(new EmailRecord("Ada@example.com"));
System.out.println(fixed.contains(new EmailRecord("ada@example.com"))); // true
}
}

The set looks in the bucket for the new object’s hash code, which is unrelated to the stored object’s, so equals never even runs. Compiling with javac -Xlint:all flags the mistake with an [overrides] warning, which is worth mentioning as the cheap way to catch it. The record fixes it because, as JEP 395 describes, records acquire equals, hashCode and toString from their components automatically, and the compact constructor normalizes the value before those methods see it.

How does HashMap work, and is it thread-safe?

Keys are hashed into buckets. The HashMap documentation says the default load factor of 0.75 is a good tradeoff between time and space, and when the map passes its threshold it is rehashed into roughly twice as many buckets. It is not synchronized: if several threads use it and at least one modifies its structure, you must synchronize externally or use ConcurrentHashMap. Its iterators are fail-fast:

import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Map;
public class FailFast {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>(Map.of("apple", 0, "pear", 3, "fig", 0));
try {
for (String fruit : stock.keySet()) {
if (stock.get(fruit) == 0) {
stock.remove(fruit); // structural change during iteration
}
}
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException");
}
stock.values().removeIf(count -> count == 0); // the safe way
System.out.println(stock); // {pear=3}
}
}

Explain that fail-fast is a best-effort bug detector, not a concurrency guarantee: the documentation says you shouldn’t write programs that depend on the exception.

Quick-fire core questions

QuestionShort answer
Why are Strings immutable?Safe sharing, caching of hash codes, string pool
== vs equals on objectsReference identity vs logical equality
Checked vs unchecked exceptionsChecked must be declared or caught
final, finally, finalizeNo reassigning or overriding, cleanup block, deprecated hook
Why try-with-resources?Closes AutoCloseable resources even on exceptions

Modern Java questions

When would you use a record, and what are its limits?

Records are transparent carriers for data: the components define the state, the constructor, the accessors and equality. Their fields are final, but a record holding a List can still have that list mutated, so copy defensively with List.copyOf in the compact constructor. Records can’t extend other classes, though they can implement interfaces, which leads to the next question.

Show sealed interfaces with a pattern-matching switch.

public class Shapes {
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
case Rectangle(double w, double h) -> w * h; // record pattern
};
}
public static void main(String[] args) {
System.out.printf("%.2f%n", area(new Circle(1))); // 3.14
System.out.println(area(new Rectangle(2, 3))); // 6.0
}
}

Sealed classes arrived in Java 17 through JEP 409; pattern matching for switch (JEP 441) and record patterns (JEP 440) became final in Java 21. The point to make: because the compiler knows every permitted subtype, the switch needs no default, and adding a Triangle turns every incomplete switch into a compile error instead of a runtime surprise.

Concurrency questions

What are virtual threads, and when do they help?

JEP 444 made virtual threads final in Java 21. They are cheap threads managed by the JDK: when one blocks on I/O, it unmounts from its carrier platform thread, which then runs other work. They help thread-per-request code that spends most of its time waiting; they don’t make CPU-bound work faster.

import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class VirtualThreads {
public static void main(String[] args) {
AtomicInteger done = new AtomicInteger();
long start = System.nanoTime();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> executor.submit(() -> {
Thread.sleep(Duration.ofMillis(100)); // blocking call: the carrier is released
return done.incrementAndGet();
}));
} // close() waits for every task
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println(done.get() + " tasks finished, under 2 s: " + (millis < 2_000)); // 10000 tasks finished, under 2 s: true
}
}

Ten thousand blocking tasks finish in a fraction of a second because none of them holds a platform thread while it sleeps. Two pieces of JEP 444 guidance make good follow-up answers: don’t pool virtual threads, and limit concurrency with constructs designed for it, such as a Semaphore.

What is pinning, and is synchronized still a problem?

JEP 444 described two pinning cases: running inside a synchronized block or method, and running a native method or foreign function. Pinning doesn’t break correctness but can hurt scalability. JEP 491, delivered in JDK 24, lets virtual threads that block in synchronized release their carrier, which eliminates nearly all pinning. Native code and foreign functions can still pin, so the up-to-date answer depends on the JDK version in production.

Diagram of a virtual thread's lifecycle: a task runs mounted on a carrier platform thread, unmounts when it blocks on I/O so the carrier can run other virtual threads, remounts on any free carrier when the I/O completes, pins its carrier only inside native code since JDK 24, and is discarded rather than pooled when it ends, with a semaphore capping load

ConcurrentHashMap or Collections.synchronizedMap?

synchronizedMap wraps every call in one lock, and compound actions such as check-then-put still need external locking. ConcurrentHashMap allows concurrent reads and updates and offers atomic compound operations, so a shared counter becomes a single call:

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
public class WordCount {
public static void main(String[] args) {
List<String> lines = List.of("to be or not", "to be", "be quick");
Map<String, Integer> counts = new ConcurrentHashMap<>();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (String line : lines) {
executor.submit(() -> {
for (String word : line.split(" ")) {
counts.merge(word, 1, Integer::sum); // atomic per key
}
});
}
}
System.out.println(new TreeMap<>(counts)); // {be=3, not=1, or=1, quick=1, to=2}
}
}

What does volatile guarantee, and what doesn’t it?

A write to a volatile field is visible to every thread that reads the field afterwards, and it can’t be reordered around other memory operations the way plain field accesses can. It doesn’t make compound actions atomic: count++ on a volatile int is still a read, an add and a write, so two threads can lose an update. Use AtomicInteger, LongAdder for hot counters, or a lock when several fields must change together.

ThreadLocal or ScopedValue?

JEP 506 finalized scoped values in JDK 25. A scoped value is bound for the duration of a call and is immutable, while a ThreadLocal can be changed at any time and lives as long as its thread. With millions of short-lived virtual threads, scoped values are the cleaner way to pass request context such as a user ID.

Version facts worth knowing

ReleaseFeatureQuestion it prompts
Java 17Sealed classes”How is that switch exhaustive?”
Java 21Virtual threads, switch patterns”When won’t virtual threads help?”
JDK 24No pinning in synchronized”Is synchronized still a problem?”
JDK 25 (LTS)Scoped values”ThreadLocal or ScopedValue?”
JDK 27G1 default in all environments”What changed in the latest JDK?”

JDK 27 reached general availability on September 15, 2026. Most production code runs on an LTS release, so ask the interviewer which version they use before relying on newer syntax.

Rehearse the explanations

The code is the easy half; explaining why the broken set returns false is where candidates stumble. Practice with a partner or record a mock session with ExtraBrain, then read the transcript and tighten any answer that took longer than a minute. ExtraBrain can also suggest follow-up questions after an answer, such as what changes if the map is shared across threads, which is good practice for the interviewer’s next move. The backend developer mock interview page adds system design prompts, and our SQL interview questions cover the database round that often sits next to the Java one. Follow the employer’s rules on AI tools in the real interview.

FAQ

Which Java version should I use in a coding interview?

Use the version the platform runs, and avoid preview features. Records, switch expressions and var are safe on Java 17 and later.

Are Spring questions part of Java interviews?

For backend roles, often: dependency injection, bean scopes and transaction boundaries. Core language and concurrency questions still come first.

Do I need to know garbage collection details?

Know what generational collection means, what a stop-the-world pause is, and how to read a GC log at a basic level. Tuning flags matter mainly for performance-focused roles.

Should I write streams or loops?

Either is fine if it’s readable. Interviewers mostly check that you know when a stream hides complexity, for example a stateful lambda in a parallel stream.

Sources (checked November 21, 2026)