Java interview questions: core Java to Java 21, explained
The language, collections, modern Java features and concurrency questions Java developers prepare for, with short code examples.
Java interviews usually test core language behavior (== vs equals, String immutability, the equals/hashCode contract, checked vs unchecked exceptions), the collections framework (ArrayList, HashMap, ConcurrentHashMap), generics and type erasure, functional features from Java 8 (lambdas, streams, Optional), newer features such as records, sealed classes and pattern matching, and the JVM and concurrency (memory areas, garbage collection, synchronized vs volatile, thread pools, CompletableFuture, virtual threads). Below are 22 questions from basic to advanced with code examples.
Basic java interview questions
Basic1. What is the difference between the JDK, the JRE and the JVM?
The JVM (Java Virtual Machine) runs compiled bytecode and manages memory and threads. The JRE was the runtime bundle (JVM plus standard libraries) needed to run programs. The JDK adds the compiler (javac) and tools such as jshell, jar and javadoc. Since Java 11 the JDK is the standard distribution; a separate JRE download is no longer offered by Oracle.
Basic2. What is the difference between == and equals() for Strings?
== compares references: whether two variables point to the same object. equals() compares content. String literals are interned (stored once in the string pool), so two identical literals can be ==, but a String built at runtime is a new object. Always compare String content with equals().
Java · Example (not executed)String a = "java";
String b = "java";
String c = new String("java");
boolean sameLiteral = (a == b); // true: both point to the pooled literal
boolean sameObject = (a == c); // false: c is a separate object
boolean sameText = a.equals(c); // true: same charactersBasic3. Why are Strings immutable in Java?
Immutability makes Strings safe to share between threads without locking, lets the JVM cache them in the string pool, keeps their hash code stable (so they work as HashMap keys), and prevents a caller from changing a value such as a file path or URL after it has been checked. Methods such as toUpperCase() and replace() return new String objects.
Basic4. What is autoboxing, and why is Integer == Integer risky?
Autoboxing converts a primitive (int) to its wrapper (Integer) automatically, and unboxing goes the other way. Integer.valueOf caches values from -128 to 127, so == on two boxed values in that range can be true while larger equal values are false. Compare wrappers with equals(), and watch for NullPointerException when unboxing a null.
Java · Example (not executed)Integer x = 127, y = 127;
Integer p = 128, q = 128;
boolean small = (x == y); // true: both come from the Integer cache
boolean large = (p == q); // false on a default JVM: two different objects
boolean same = p.equals(q); // true: compare values with equals()
Integer missing = null;
// int n = missing; // would throw NullPointerException when unboxingBasic5. ArrayList or LinkedList: when do you use each?
ArrayList is backed by an array: get(i) is O(1) and adding at the end is amortized O(1), but inserting or removing in the middle shifts elements. LinkedList is a doubly linked list: inserting or removing at a known node is O(1), but get(i) walks the list. In practice ArrayList (or ArrayDeque for queues) is the right default because it is cache-friendly.
Basic6. How does a HashMap work?
A HashMap stores entries in an array of buckets. It computes the key's hashCode, spreads the bits, and picks a bucket; equal keys are found with equals(). Collisions share a bucket, and since Java 8 a bucket with many collisions is converted to a balanced tree, so lookups stay fast. When the map grows past its load factor (0.75 by default) it resizes and rehashes. HashMap allows one null key and is not thread-safe.
Basic7. What is the contract between equals() and hashCode()?
If two objects are equal according to equals(), they must return the same hashCode(). Unequal objects may share a hash code, but fewer collisions is better. Breaking the contract makes HashMap and HashSet lose or duplicate entries. Override both together, based on the same fields, and keep those fields immutable while the object is in a hash-based collection.
Java · Example (not executed)import java.util.Objects;
final class Point {
private final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point p)) return false; // pattern matching for instanceof (Java 16)
return x == p.x && y == p.y;
}
@Override public int hashCode() { return Objects.hash(x, y); }
}Basic8. What is the difference between checked and unchecked exceptions?
Checked exceptions (subclasses of Exception but not RuntimeException, such as IOException) must be caught or declared with throws: the compiler enforces it. Unchecked exceptions (RuntimeException and its subclasses, such as NullPointerException or IllegalArgumentException) signal programming errors and need no declaration. Errors (such as OutOfMemoryError) are serious problems an application usually should not catch. try-with-resources closes resources automatically.
Java · Example (not executed)import java.io.*;
import java.nio.file.*;
static String firstLine(Path file) throws IOException { // checked: must be declared
try (BufferedReader r = Files.newBufferedReader(file)) { // closed automatically
return r.readLine();
}
}
static int parse(String s) {
if (s == null) throw new IllegalArgumentException("s is null"); // unchecked
return Integer.parseInt(s);
}Intermediate java interview questions
Intermediate9. What is the difference between final, finally and finalize?
final makes a variable unassignable after initialization, a method impossible to override, or a class impossible to extend. finally is a block that runs after try (and catch) whether or not an exception was thrown, typically for cleanup. finalize() was a method the garbage collector might call before reclaiming an object; it is unreliable and was deprecated for removal in Java 18 (JEP 421). Use try-with-resources or Cleaner instead.
Intermediate10. Interface or abstract class: how do you choose?
An interface defines a capability that unrelated classes can implement, and a class can implement many interfaces. Since Java 8 interfaces can have default and static methods, and since Java 9 private methods, but they cannot hold instance state. An abstract class can hold state and constructors and share implementation, but a class can extend only one. Prefer interfaces for types and abstract classes for shared partial implementations.
Intermediate11. What is type erasure in generics?
Generic type information is checked at compile time and then erased: at runtime a List<String> and a List<Integer> are both just List. That is why you cannot write new T(), use instanceof with a parameterized type, or overload methods that differ only by type arguments. Wildcards express variance: ? extends T for reading (producer), ? super T for writing (consumer), often remembered as PECS.
Java · Example (not executed)import java.util.*;
static double sum(List<? extends Number> nums) { // producer: read Numbers
double total = 0;
for (Number n : nums) total += n.doubleValue();
return total;
}
static void fill(List<? super Integer> out) { // consumer: write Integers
for (int i = 0; i < 3; i++) out.add(i);
}
// boolean same = new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass(); // true: erasedIntermediate12. How do Java streams work?
A stream is a pipeline over a data source: intermediate operations (filter, map, sorted) are lazy and return a new stream, and nothing runs until a terminal operation (collect, count, forEach, reduce). A stream can be consumed only once. Streams do not modify their source; parallel streams split the work across threads but help only for large, CPU-bound, side-effect-free work.
Java · Example (not executed)import java.util.*;
import java.util.stream.*;
record Employee(String name, String team, int salary) {}
List<Employee> staff = List.of(
new Employee("Ava", "eng", 150_000), new Employee("Ben", "eng", 120_000),
new Employee("Dev", "sales", 95_000));
Map<String, List<String>> namesByTeam = staff.stream()
.filter(e -> e.salary() > 100_000)
.collect(Collectors.groupingBy(Employee::team,
Collectors.mapping(Employee::name, Collectors.toList())));
// namesByTeam is {eng=[Ava, Ben]}Intermediate13. How should Optional be used?
Optional is a return type that says a value may be absent, forcing the caller to handle that case with map, filter, orElse, orElseGet or orElseThrow. Avoid calling get() without checking, and avoid Optional for fields, parameters and collections (return an empty collection instead). orElse evaluates its argument eagerly; orElseGet only when needed.
Java · Example (not executed)import java.util.*;
static Optional<String> findEmail(Map<String, String> emails, String user) {
return Optional.ofNullable(emails.get(user));
}
String domain = findEmail(Map.of("ava", "ava@example.com"), "ava")
.map(e -> e.substring(e.indexOf('@') + 1))
.orElse("unknown"); // "example.com"Intermediate14. What is a record?
A record (standard since Java 16, JEP 395) is a concise, immutable data carrier: the compiler generates the private final fields, a canonical constructor, accessors, equals(), hashCode() and toString() from the component list. You can add validation in a compact constructor and add methods, but records cannot extend another class or declare extra instance fields.
Java · Example (not executed)record Range(int lo, int hi) {
Range { // compact constructor: validation
if (lo > hi) throw new IllegalArgumentException("lo > hi");
}
int length() { return hi - lo; }
}
Range r = new Range(2, 5);
// r.lo() is 2, r.length() is 3, and new Range(2, 5).equals(r) is trueIntermediate15. Comparable or Comparator?
Comparable defines a class's natural ordering through compareTo, implemented by the class itself (String and Integer implement it). Comparator is a separate object that defines an ordering, so you can sort the same type several ways; Comparator.comparing, thenComparing and reversed compose them. Keep compareTo consistent with equals where possible.
Java · Example (not executed)import java.util.*;
record Candidate(String name, int years) {}
List<Candidate> list = new ArrayList<>(List.of(
new Candidate("Cara", 3), new Candidate("Ava", 5), new Candidate("Ben", 3)));
list.sort(Comparator.comparingInt(Candidate::years).reversed()
.thenComparing(Candidate::name));
// order: Ava (5), Ben (3), Cara (3)Advanced java interview questions
Advanced16. What are sealed classes, and how do they work with switch?
A sealed class or interface (Java 17, JEP 409) lists exactly which classes may extend or implement it with permits. Combined with records and pattern matching for switch (Java 21, JEP 441), the compiler knows every possible subtype, so a switch over a sealed type can be exhaustive without a default branch, and adding a new subtype makes the old switch fail to compile until you handle it.
Java · Example (not executed)sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
static double area(Shape s) {
return switch (s) { // exhaustive: no default needed
case Circle c -> Math.PI * c.r() * c.r();
case Square q -> q.side() * q.side();
};
}Advanced17. How is JVM memory organized, and how does garbage collection work?
Each thread has a stack holding frames with local variables and references; objects live on the shared heap; class metadata lives in metaspace (which replaced PermGen in Java 8). Garbage collectors reclaim objects that are no longer reachable from roots such as stacks and static fields. The standard collectors are generational, because objects usually die young. G1 has been the default collector since Java 9; ZGC and Shenandoah target very low pause times.
Advanced18. What is the difference between synchronized and volatile?
volatile ensures visibility: a write to a volatile field is seen by later reads in other threads, and it prevents certain reorderings, but it does not make compound actions such as count++ atomic. synchronized gives mutual exclusion and visibility: only one thread holds the monitor at a time. For counters, AtomicInteger or LongAdder are simpler and faster than locking.
Java · Example (not executed)import java.util.concurrent.atomic.AtomicInteger;
class Counters {
private volatile boolean running = true; // visibility flag: fine
private int unsafe = 0; // unsafe++ from many threads loses updates
private int locked = 0;
private final AtomicInteger atomic = new AtomicInteger();
synchronized void incLocked() { locked++; }
void incAtomic() { atomic.incrementAndGet(); }
void stop() { running = false; }
}Advanced19. How do thread pools and virtual threads differ?
An ExecutorService reuses a fixed or bounded set of platform threads, which are expensive operating-system threads, so you size the pool for the work. Virtual threads (Java 21, JEP 444) are lightweight threads scheduled by the JVM; you can create one per task, and blocking I/O no longer ties up an OS thread. They suit I/O-heavy servers, not CPU-bound work, and you should still limit access to scarce resources such as database connections.
Java · Example (not executed)import java.util.concurrent.*;
import java.util.stream.IntStream;
// Java 21: one virtual thread per task
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i ->
ex.submit(() -> { Thread.sleep(100); return i; }));
} // close() waits for submitted tasks to finish
// classic bounded pool for CPU-bound work
ExecutorService cpu = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());Advanced20. How do you compose asynchronous work with CompletableFuture?
CompletableFuture represents a result that will be available later. thenApply transforms a result, thenCompose chains another asynchronous step, thenCombine joins two independent results, allOf waits for many, and exceptionally or handle deal with failures. Pass your own Executor for blocking work instead of relying on the common pool.
Java · Example (not executed)import java.util.concurrent.*;
ExecutorService io = Executors.newFixedThreadPool(8);
CompletableFuture<String> profile = CompletableFuture.supplyAsync(() -> fetchProfile(42), io);
CompletableFuture<Integer> score = CompletableFuture.supplyAsync(() -> fetchScore(42), io);
CompletableFuture<String> summary = profile
.thenCombine(score, (p, s) -> p + " scored " + s)
.exceptionally(err -> "unavailable: " + err.getMessage());Advanced21. ConcurrentHashMap or Collections.synchronizedMap?
Collections.synchronizedMap wraps a map with a single lock, so every operation is serialized and you must lock manually while iterating. ConcurrentHashMap allows concurrent reads and fine-grained concurrent writes, its iterators never throw ConcurrentModificationException, and it offers atomic compound operations such as computeIfAbsent and merge. It does not allow null keys or values.
Advanced22. What causes a deadlock, and how do you prevent one?
A deadlock happens when threads each hold a lock the other needs and wait forever. It requires mutual exclusion, hold-and-wait, no preemption and a circular wait. Prevent it by always acquiring locks in the same global order, holding locks for as short a time as possible, using tryLock with a timeout, or using higher-level concurrency utilities. A thread dump (jstack) shows deadlocked threads.
How to practice with this page
- Type each example into a Java 21 project (or jshell) and check what it does before reading the answer again.
- For each collection, be ready to state its time complexity for get, add and contains.
- Explain one concurrency bug you could cause with an unsynchronized counter, and two ways to fix it.
- Pair this page with the system design questions for senior backend roles.
Related interview prep
Framework and trade-offs.
Open →QuestionsSQL interview questionsJoins to window functions, with real output.
Open →RoleComputer programmer interview questionsRole-specific questions.
Open →RoleSoftware engineer interview questionsThe questions engineers prepare for.
Open →Disclosure: TryHired makes HIRED, a paid job-search program, so we have a conflict of interest when we mention it. This question bank is free, with no TryHired signup.
Questions people ask
What Java questions are asked in interviews?
Which Java version should I prepare for?
Are the code examples on this page tested?
How do I prepare for a Java coding interview?
Is Java the same as JavaScript?
How this page is built
TryHired wrote these questions and answers. Blocks marked Example (not executed) are code that could not run on the build machine (no Java runtime, no React runtime): no output is claimed for them. The question list is general practice: it does not predict what a particular employer will ask.
- Interviewers ask different questions for different roles and levels.
- Answers are short explanations, not complete references.
- No Java runtime was available when this page was built: the Java blocks are examples, not executed, and no output is claimed for them.
- Feature availability depends on the Java version a team runs; the version that introduced each feature is named where it matters.
- Oracle, The Java Tutorials and Java SE API documentation: https://docs.oracle.com/en/java/javase/21/
- OpenJDK JEP 395, Records: https://openjdk.org/jeps/395
- OpenJDK JEP 409, Sealed Classes: https://openjdk.org/jeps/409
- OpenJDK JEP 441, Pattern Matching for switch: https://openjdk.org/jeps/441
- OpenJDK JEP 444, Virtual Threads: https://openjdk.org/jeps/444
- OpenJDK JEP 421, Deprecate Finalization for Removal: https://openjdk.org/jeps/421