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.

Updated November 20, 2026 35 questions 8 min read

Key takeaways

  • Java interviews start with OOP, equals/hashCode and 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

Typical topic mix in a Java backend interview

Editorial estimate; senior loops add system design rounds.

45–60minutes
  • Core Java and OOP20%
  • Collections and generics20%
  • Concurrency20%
  • JVM and memory10%
  • Spring and persistence15%
  • Coding exercise15%

Choosing a collection

Which collection to use
NeedUseComplexity of the key operation
Ordered list, index accessArrayListget O(1)
Queue or stackArrayDequepush/pop O(1)
Key-value lookupHashMapget/put O(1) average
Sorted keys, range queriesTreeMapO(log n)
Insertion order or LRULinkedHashMapO(1) average
Shared between threadsConcurrentHashMapO(1) average
Priority processingPriorityQueueoffer/poll O(log n)

See also backend interview questions and system design questions.

Core Java and OOP

1What are the four principles of OOP?

Junior

Encapsulation 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?

Junior

The 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?

Junior

A 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?

Mid

Hash-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?

Junior

Immutability 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?

Junior

Overloading: 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?

Mid

Records 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?

Junior

Always 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?

Mid

Keys 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?

Junior

ArrayList 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?

Mid

HashMap: 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?

Mid

Iterators 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?

Mid

Generic 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?

Junior

Checked 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?

Junior

A 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?

Mid

Catch 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?

Mid

Streams 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?

Mid

map 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?

Mid

As 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?

Senior

For 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?

Mid

Visibility 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?

Mid

synchronized 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?

Mid

A 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?

Mid

ExecutorService 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?

Senior

Lightweight 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?

Senior

Two 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?

Mid

Each 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?

Senior

The 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?

Senior

Enable 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?

Senior

Rules 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?

Mid

Objects 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?

Mid

Spring 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?

Senior

Loading 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.

Mid
List<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.

Senior

The 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

  1. Know the collections frameworkHashMap internals, equals/hashCode, and when to use each collection.
  2. Practice concurrency explanationsvolatile vs synchronized, ConcurrentHashMap, executors, virtual threads.
  3. Prepare a JVM storyA time you debugged memory, GC pauses or performance with real tools.
  4. Review modern JavaRecords, sealed classes, pattern matching, text blocks, var.
  5. 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.

Related interview questions