Java Interview Questions and Answers
35 Java interview questions with answers and code: OOP, equals and hashCode, collections, generics, exceptions, streams, concurrency, JVM memory and garbage collection, Spring basics.
Key takeaways
- Java interviews start with OOP,
equals/hashCodeand the collections framework; expect them at every level. - HashMap internals and ConcurrentHashMap are among the most frequent mid-level questions.
- Senior interviews go deep into concurrency, the Java memory model, JVM tuning and garbage collection.
- Backend roles usually add Spring Boot, transactions and REST API design.
Contents
Java interviews move from OOP and collections for juniors to concurrency, the JVM and Spring for senior backend roles. Below are 35 common questions grouped by topic and level, with answers and code.
What Java interviews cover
Editorial estimate; senior loops add system design rounds.
- Core Java and OOP20%
- Collections and generics20%
- Concurrency20%
- JVM and memory10%
- Spring and persistence15%
- Coding exercise15%
Choosing a collection
| Need | Use | Complexity of the key operation |
|---|---|---|
| Ordered list, index access | ArrayList | get O(1) |
| Queue or stack | ArrayDeque | push/pop O(1) |
| Key-value lookup | HashMap | get/put O(1) average |
| Sorted keys, range queries | TreeMap | O(log n) |
| Insertion order or LRU | LinkedHashMap | O(1) average |
| Shared between threads | ConcurrentHashMap | O(1) average |
| Priority processing | PriorityQueue | offer/poll O(log n) |
See also backend interview questions and system design questions.
Core Java and OOP
1What are the four principles of OOP?
JuniorEncapsulation hides internal state behind methods. Inheritance reuses behavior from a parent class. Polymorphism lets one interface have many implementations. Abstraction exposes what an object does, not how. In interviews, give a short example of each from real code.
2JDK vs JRE vs JVM?
JuniorThe JVM runs bytecode. The JRE is the JVM plus the standard libraries needed to run programs. The JDK adds development tools such as the compiler (javac). Modern Java distributions ship the JDK; a separate JRE is rarely installed.
3Abstract class vs interface?
JuniorA class can implement many interfaces but extend only one class. Interfaces define a contract and can have default and static methods; abstract classes can also hold state and constructors. Prefer interfaces for capabilities, abstract classes for shared base implementation.
4Why must you override hashCode when you override equals?
MidHash-based collections first use hashCode to find a bucket, then equals inside it. Equal objects must have equal hash codes; otherwise a HashSet can contain “duplicates” and HashMap.get can fail to find a key you just put in.
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point p)) return false;
return x == p.x && y == p.y;
}
@Override public int hashCode() { return Objects.hash(x, y); }
5Why is String immutable?
JuniorImmutability makes strings safe to share between threads, allows the string pool to reuse instances, and makes them reliable keys in hash maps (their hash code is cached). Use StringBuilder for building strings in loops.
6Overloading vs overriding?
JuniorOverloading: same method name with different parameters in one class, resolved at compile time. Overriding: a subclass provides its own implementation of an inherited method with the same signature, resolved at runtime.
7What are records and sealed classes?
MidRecords are concise immutable data carriers: record Point(int x, int y) {} generates constructor, accessors, equals, hashCode and toString. Sealed classes restrict which classes can extend them, which works well with pattern matching in switch.
8Is Java pass-by-value or pass-by-reference?
JuniorAlways pass-by-value. For objects, the value passed is a copy of the reference, so a method can modify the object but can’t make the caller’s variable point to a different object.
Collections and generics
9How does HashMap work internally?
MidKeys are hashed into an array of buckets. Collisions are stored in a linked list per bucket, which turns into a balanced tree when a bucket grows large, keeping worst-case lookup at O(log n). When the size exceeds capacity times the load factor (0.75 by default), the table is resized and entries are redistributed.
10ArrayList vs LinkedList?
JuniorArrayList is backed by an array: fast random access and good cache locality. LinkedList has fast insertion at known positions, but slow access by index. In practice ArrayList (or ArrayDeque for queues) is almost always the better choice.
11HashMap vs LinkedHashMap vs TreeMap?
MidHashMap: no order, O(1) average operations. LinkedHashMap: keeps insertion (or access) order, useful for LRU caches. TreeMap: keys sorted, O(log n) operations, supports range queries like headMap and ceilingKey.
12What is a fail-fast iterator?
MidIterators of most collections throw ConcurrentModificationException if the collection is structurally modified during iteration (except through the iterator’s own remove). Concurrent collections use fail-safe or weakly consistent iterators instead.
13What is type erasure in generics?
MidGeneric type information is checked at compile time and erased at runtime, so List<String> and List<Integer> are the same class. That’s why you can’t do new T() or instanceof List<String>. Wildcards (? extends, ? super) express variance: “producer extends, consumer super”.
Get Java answer points in real time during your interview
Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.
Exceptions
14Checked vs unchecked exceptions?
JuniorChecked exceptions (IOException) must be declared or caught; they represent recoverable conditions. Unchecked exceptions (RuntimeException and subclasses) usually indicate programming errors. Error (like OutOfMemoryError) shouldn’t normally be caught.
15What is try-with-resources?
JuniorA try statement that automatically closes resources implementing AutoCloseable, even when an exception is thrown:
try (var reader = Files.newBufferedReader(path)) {
return reader.readLine();
}
16What are good practices for exception handling?
MidCatch only what you can handle, keep the original cause when wrapping (new ServiceException("...", e)), don’t swallow exceptions silently, avoid using exceptions for normal control flow, and log once at the boundary rather than at every level.
Streams and functional Java
17What are streams, and how do intermediate and terminal operations differ?
MidStreams process collections declaratively. Intermediate operations (filter, map, sorted) are lazy and return a stream; a terminal operation (collect, count, forEach) triggers the processing.
Map<String, Long> byDept = employees.stream()
.filter(e -> e.salary() > 50_000)
.collect(Collectors.groupingBy(Employee::dept, Collectors.counting()));
18map vs flatMap?
Midmap transforms each element into one element. flatMap transforms each element into a stream and flattens the results, for example turning a list of orders into a stream of all their items.
19How should you use Optional?
MidAs a return type for values that may be absent, with map, orElse and orElseThrow. Avoid it for fields, method parameters and collections (return an empty collection instead), and avoid calling get() without a check.
20When are parallel streams a bad idea?
SeniorFor small collections, I/O-bound work, operations with shared mutable state, or inside a server where the common ForkJoin pool is shared with other tasks. Measure before using them; often an explicit executor is more predictable.
Concurrency
21What does volatile guarantee?
MidVisibility and ordering: writes to a volatile field are immediately visible to other threads, and reordering around it is restricted. It does not make compound operations like count++ atomic; use AtomicInteger or locks for that.
22synchronized vs ReentrantLock?
Midsynchronized is simple and automatically released. ReentrantLock adds features: tryLock with a timeout, interruptible locking, fairness and multiple conditions. Use synchronized unless you need those features.
23How does ConcurrentHashMap differ from a synchronized map?
MidA synchronized map locks the whole map for each operation. ConcurrentHashMap allows concurrent reads and fine-grained locking on writes, and provides atomic operations like computeIfAbsent and merge. Its iterators are weakly consistent and don’t throw ConcurrentModificationException.
24What are ExecutorService and CompletableFuture?
MidExecutorService manages a pool of threads to run tasks. CompletableFuture composes asynchronous results: supplyAsync, thenApply, thenCombine, allOf, with error handling through exceptionally.
25What are virtual threads?
SeniorLightweight threads managed by the JVM (final in Java 21). You can create millions of them, so blocking code that waits on I/O scales without callback-style async code. They don’t speed up CPU-bound work, and long blocking inside synchronized sections can pin them to carrier threads.
26What is a deadlock, and how do you prevent it?
SeniorTwo or more threads each wait for a lock the other holds. Prevent it by acquiring locks in a consistent global order, using tryLock with timeouts, keeping critical sections small, and preferring higher-level concurrency utilities. Thread dumps show deadlocked threads.
JVM and memory
27Heap vs stack memory?
MidEach thread has its own stack holding method frames and local primitive values and references. Objects live on the shared heap and are managed by the garbage collector. A StackOverflowError usually means deep recursion; OutOfMemoryError means the heap (or another memory area) is exhausted.
28How does garbage collection work?
SeniorThe GC finds objects that are no longer reachable from roots (thread stacks, static fields) and reclaims them. Most collectors are generational, because most objects die young. G1 is the default in modern JDKs; ZGC and Shenandoah target very low pause times for large heaps.
29How do you investigate a memory leak or high GC activity?
SeniorEnable GC logging, watch heap usage over time, and take a heap dump (jcmd <pid> GC.heap_dump) to analyze in a tool like Eclipse MAT. Typical causes: unbounded caches, static collections, listeners never removed, and ThreadLocal values in thread pools.
30What is the Java Memory Model’s happens-before relationship?
SeniorRules that guarantee when one thread’s writes are visible to another: unlocking a monitor happens-before a later lock of it, a volatile write happens-before a later read, starting a thread happens-before its actions, and so on. Without such a relationship, threads may see stale or reordered values.
Spring and backend
31What is dependency injection, and how does Spring implement it?
MidObjects receive their dependencies instead of creating them, which makes code testable and loosely coupled. Spring creates beans and injects them, preferably through constructors. Annotations like @Service and @Repository mark beans; @Configuration classes define them explicitly.
32How does @Transactional work, and what are common pitfalls?
MidSpring wraps the bean in a proxy that starts and commits (or rolls back) a transaction around the method. Pitfalls: calling a @Transactional method from the same class bypasses the proxy; checked exceptions don’t trigger rollback by default; and long transactions hold database locks.
33What is the N+1 query problem in JPA, and how do you fix it?
SeniorLoading a list of entities and then lazily loading a relation for each one triggers one query plus N more. Fix it with fetch joins (JOIN FETCH), entity graphs, batch fetching, or DTO projections that load exactly what you need.
Coding exercises
34Count word frequencies and return the top 3.
MidList<String> top3 = Arrays.stream(text.toLowerCase().split("\\W+"))
.filter(w -> !w.isBlank())
.collect(Collectors.groupingBy(w -> w, Collectors.counting()))
.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.limit(3)
.map(Map.Entry::getKey)
.toList();
35Implement a thread-safe singleton.
SeniorThe simplest correct options are an enum singleton or the holder idiom, which relies on class initialization being thread-safe:
public final class Config {
private Config() {}
private static class Holder { static final Config INSTANCE = new Config(); }
public static Config getInstance() { return Holder.INSTANCE; }
}
Mention that dependency injection usually makes hand-written singletons unnecessary.
How to prepare
- Know the collections frameworkHashMap internals, equals/hashCode, and when to use each collection.
- Practice concurrency explanationsvolatile vs synchronized, ConcurrentHashMap, executors, virtual threads.
- Prepare a JVM storyA time you debugged memory, GC pauses or performance with real tools.
- Review modern JavaRecords, sealed classes, pattern matching, text blocks,
var. - For backend roles, revise SpringDI, transactions, JPA pitfalls and REST design.
Get answer points in real time during your interview
Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.