Top 50 Java Collections Interview Questions and Answers (2026 Edition)

Top 50 Java Collections Interview Questions and Answers (2026 Edition) Work through these 50 questions out loud. Open any question for the full model answer, the trap to avoid, and the follow-up a panel usually asks.

  1. What are compact source files and instance main methods in JDK 25, and would you use them at work?

    I would use compact mains for katas, jbang-style tools, and interview warm-ups. I would not structure a payment service that way. On a panel I say: JDK 25 made this standard so...

    Full answer

  2. What do module import declarations in JDK 25 change, and how is that different from wildcard type imports?

    In a compact demo I might import module java.base and java.sql. In a Spring service I keep explicit package imports — reviewers grep those. I would not claim it replaces JPMS...

    Full answer

  3. Explain the difference between == and .equals() in Java.

    For primitives, == compares values. For objects, == asks if two references point to the same instance. equals() compares content when overridden — String overrides it for...

    Full answer

  4. What is the N+1 query problem and how do you fix it?

    Loading 100 orders then accessing each order's items triggers 101 queries. Fix with JOIN FETCH in JPQL, @EntityGraph on repository method, or a DTO query selecting only...

    Full answer

  5. HashMap vs ConcurrentHashMap — when and why?

    HashMap for single-threaded or external synchronization. ConcurrentHashMap for shared concurrent maps — finer-grained locking than Hashtable. Cannot store null keys/values in...

    Full answer

  6. What is the difference between ArrayList and LinkedList?

    ArrayList: dynamic array, great for get(i) and iteration, amortized append. LinkedList: node chain, costly random access, only wins for frequent insert/remove in middle with...

    Full answer

  7. What is the difference between Comparable and Comparator?

    Comparable built into the type — Employee implements compareTo by id. Comparator external — sort by name or salary without changing Employee. Use...

    Full answer

  8. Explain garbage collection basics in the JVM.

    New objects allocate in Eden; minor GC copies survivors to survivor spaces, then old gen. When old gen fills, major/full GC runs — longer pauses. Tune -Xmx, choose G1 for...

    Full answer

  9. When should you use CopyOnWriteArrayList?

    Use for subscriber lists in pub/sub where adds are rare and iteration is constant. Avoid for high-frequency add/remove — use ConcurrentLinkedQueue or synchronized collections....

    Full answer

  10. What are weak references and WeakHashMap use cases?

    Attach metadata to objects without extending their lifetime — canonical mapping while object lives. When key GCs, entry drops. Do not rely on timing. For API response caching...

    Full answer

  11. Compare BlockingQueue implementations for producer-consumer workloads.

    For order processing, use ArrayBlockingQueue with capacity matching SLA — slow consumer blocks producer instead of OOM. ThreadPoolExecutor with SynchronousQueue +...

    Full answer

  12. IdentityHashMap vs HashMap — when would you use IdentityHashMap?

    Use when identity matters not value — tracking object visitation in deep graph walk. Business keys (userId, email) belong in HashMap with proper equals/hashCode....

    Full answer

  13. Lazy vs eager fetching in JPA — trade-offs?

    Default associations LAZY. Service method needing orders+items uses JOIN FETCH in repository query. Disable spring.jpa.open-in-view=false — forces explicit fetch in service...

    Full answer

  14. Load shedding and backpressure in microservices?

    Tomcat max queue + reject policy returns 503 with Retry-After. WebClient timeout + circuit breaker stops calling slow dependency. Kafka consumer pause partitions when...

    Full answer

  15. Stream.toList() vs Collectors.toList() in modern Java?

    Public API return users.stream().filter(...).toList() — immutable contract. Internal processing needing mutation: collect(Collectors.toList()). Java 21+ sequenced collections...

    Full answer

  16. Your application memory usage keeps increasing over time. What do you suspect?

    Suspect memory leak if heap used grows after GC without traffic drop. Capture heap dump on OOM (`-XX:+HeapDumpOnOutOfMemoryError`), compare dominator tree. Common in Spring:...

    Full answer

  17. What are sequenced collections in JDK 21, and which calls replace fragile index access?

    I reach for getFirst/getLast on lists and deques instead of magic indexes. For a recent-activity map I use LinkedHashMap as a SequencedMap and pollFirstEntry to evict oldest....

    Full answer

  18. Explain immutability and why String is immutable.

    Immutable objects cannot change after build — thread-safe without synchronization. String immutability allows intern pool, caching hashCode, and security when used as...

    Full answer

  19. volatile vs synchronized — when to use each?

    volatile for single-writer flags (shutdown, initialized) where no read-modify-write. synchronized or java.util.concurrent locks when multiple threads update shared state. For...

    Full answer

  20. What is Optional and when should you use it?

    Use Optional as return type when absence is expected — findById returns Optional<User>. Chain with map/flatMap/orElseThrow. Do not use for fields, method parameters, or Jackson...

    Full answer

  21. Explain method overloading vs overriding.

    Overload print(int) and print(String) in one class — compiler picks at compile time. Override toString in subclass — JVM calls subclass version via virtual method table....

    Full answer

  22. How does Stream API parallel stream work?

    parallelStream() splits work across common pool threads. Good for CPU-heavy map on large in-memory collections. Bad for small lists, IO inside stream, or ordered stateful...

    Full answer

  23. What is an ExecutorService and why use it?

    Instead of new Thread per task, submit Runnable to fixed pool sized to CPU/IO profile. Handle Future results and exceptions. On shutdown hook call shutdown() and...

    Full answer

  24. What are virtual threads in Java 21 and when should you use them?

    Virtual threads excel when code blocks on IO — HTTP clients, JDBC, file reads — allowing one platform thread to serve thousands of concurrent requests. For CPU-heavy parallel...

    Full answer

  25. Explain sealed classes and their purpose in Java 17+.

    sealed interface Shape permits Circle, Rectangle limits who implements Shape. Compiler verifies switch (Shape s) covers all cases — no default needed. Use for domain variants...

    Full answer

  26. What is pattern matching for switch (Java 21)?

    Instead of if (obj instanceof String s) { ... }, use switch (obj) { case String s when s.length() > 5 -> ...; case String s -> ...; case null -> ...; default -> ... }. Works...

    Full answer

  27. Why is ThreadLocal problematic with virtual threads?

    Libraries storing per-request state in ThreadLocal allocate one entry per virtual thread — catastrophic memory with 100k concurrent requests. Prefer ScopedValue for request...

    Full answer

  28. How do CompletableFuture and virtual threads compare for concurrency?

    Use virtual threads when business logic is naturally blocking — call DB, call HTTP, return. Use CompletableFuture when composing multiple independent async results with...

    Full answer

  29. Explain the happens-before relationship in the Java Memory Model.

    Thread A writes x=1 without sync; Thread B reads x may see 0 forever. volatile x or synchronized block creates happens-before. Classic DCL singleton needs volatile instance...

    Full answer

  30. What are text blocks and how do they improve Java code?

    String query = """ SELECT u.id, u.name FROM users u WHERE u.active = true """; — readable without \n concatenation. Use formatted for parameters carefully — prefer...

    Full answer

  31. Explain structured concurrency and why it matters.

    In a request handler, open StructuredTaskScope, fork fetchUser and fetchOrders, join both — if orders fail, user fetch cancelled automatically. Safer than manual Future...

    Full answer

  32. AtomicReference vs synchronized — when to choose each?

    Use AtomicReference for lock-free config pointer swap — compareAndSet(old, new). Use synchronized when updating multiple related fields atomically. AtomicInteger for counters....

    Full answer

  33. What is the Java Platform Module System (JPMS) and who needs it?

    Use modules when building custom JDK images or publishing strict API boundaries. Typical microservice: no module-info — Spring Boot repackages classpath. Watch for illegal...

    Full answer

  34. What are ScopedValues and how do they replace ThreadLocal?

    Replace logging MDC ThreadLocal with ScopedValue.where(REQUEST_ID, id).run(() -> handle()). Value immutable — update by nesting new scope. Frameworks (Spring, Micrometer)...

    Full answer

  35. What is ForkJoinPool common pool starvation and how do you avoid it?

    Never block on common pool — no DB/HTTP in parallelStream without custom pool. Use Executors.newFixedThreadPool for blocking batch jobs. CompletableFuture.supplyAsync(task,...

    Full answer

  36. Explain try-with-resources and suppressed exceptions.

    try (Connection c = ds.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) { ... } — both closed even on SQLException. Check e.getSuppressed() in logs for close...

    Full answer

  37. Compare G1, ZGC, and Shenandoah garbage collectors.

    Default G1 fine for most Spring Boot services — tune -XX:MaxGCPauseMillis=200. Payment API p99 SLA <10ms GC pause: try -XX:+UseZGC on Java 21 large heap. Benchmark with JMH and...

    Full answer

  38. What is Metaspace and how do class loading issues cause memory leaks?

    Production set MaxMetaspaceSize 256m with monitoring. Investigate Metaspace OOM: heap dump + classloader histogram. Avoid generating unlimited dynamic proxies. OSGi/script...

    Full answer

  39. JVM container awareness and memory settings for Kubernetes?

    Container limit 1Gi: JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=75.0 -XX:InitialRAMPercentage=50.0. Monitor container memory vs heap used in Actuator metrics. Leave headroom for...

    Full answer

  40. Explain JIT compilation tiers (C1, C2) and warmup.

    JMH @Warmup iterations required. Production: readiness probe after warmup traffic or use Kubernetes minReadySeconds. Serverless: GraalVM native or tiered warmup requests....

    Full answer

  41. What do Java Records provide and their limitations?

    DTO: record UserResponse(String id, String name) {} — JSON mapping works. Service layer immutable value objects. Not for entities needing setters/lazy proxies yet. Combine with...

    Full answer

  42. Optional.orElseGet vs orElse — why it matters?

    Wrong: cache.orElse(loadFromDb(key)). Right: cache.orElseGet(() -> loadFromDb(key)). Constant default: orElse(Collections.emptyList()). Chain map/flatMap before orElseGet for...

    Full answer

  43. What did text blocks change in JDK 15, and where do they still go wrong in production?

    I use text blocks for SQL, JSON fixtures, and HTML snippets in tests so the source matches the payload. I keep the closing """ at the column I want as the left edge. For JSON I...

    Full answer

  44. Sealed classes were a JDK 15 preview — what problem do they solve, and what shipped later?

    On 15 I would mention it as preview — I would not ship --enable-preview in production. On 17+ I seal domain events: sealed interface LedgerEvent permits Posted, Reversed,...

    Full answer

  45. What are hidden classes in JDK 15, and which runtime frameworks rely on them?

    I do not write hidden classes in business code. I know JDK 15+ lambdas and several proxy libraries use them so generated bytecode unloads cleanly. If a heap dump shows...

    Full answer

  46. Which JVM and library changes in JDK 15 show up in production ops, not just language trivia?

    If we touched 15 on the way to 17/21, I check three ops items: collector is no longer experimental so flags change, ZGC may uncommit so RSS graphs look different, and any...

    Full answer

  47. Why is JDK 21 the LTS pin for Spring Boot 3.2+, and when are virtual threads the wrong default?

    We pin JDK 21 because it is LTS and Boot 3.2+ is built for it. I turn on virtual threads for blocking I/O APIs, keep Hikari at a DB-safe size, and put a Semaphore bulkhead in...

    Full answer

  48. How do pattern matching for switch and record patterns change JDK 21 domain code?

    For a sealed LedgerEvent I switch on Posted, Reversed, Voided and bind record components in the case. Adding a fourth event fails compilation until I handle it — that is the...

    Full answer

  49. What did generational ZGC change in JDK 21, and when would you pick it over G1?

    For a large-heap, latency-sensitive API I trial generational ZGC in staging: p99 pause, allocation rate, and RSS. I keep G1 if throughput or CPU is the SLO. I never flip...

    Full answer

  50. JDK 25 ScopedValue vs ThreadLocal — what changes in a thread-pool or virtual-thread service?

    Request tenant, correlation id, and security principal go in a ScopedValue.where(CTX, ctx).run(...) around the work. I do not set ThreadLocal in a filter and hope finally runs....

    Full answer

Java Collections Interview Questions and Answers · Top 40 Java Collections Interview Questions | Must-Prepare before interview. · Java Collections Interview Questions Every Fresher Must Know · Java Collections Interview Questions for 2–3 Years

All interview question lists · Interview guides · Home · Support the platform