Interview questions · Tech stack

Java (5 Years Experience) Interview Questions & Answers (2026)

These interviews test deep knowledge of Java language features, JVM internals, multithreading, collections, and best‑practice design patterns. Demonstrate problem‑solving ability, explain trade‑offs, and show how you apply concepts to real‑world code. Focus on clear reasoning, performance impact, and maintainable solutions to impress interviewers.

25 questions · updated Aug 29, 2026

Quick facts

Typical roundsPhone screen, coding challenge, system design, deep‑dive Java, and culture fit
Core focusConcurrency, JVM tuning, collections, streams, and design patterns
Preparation time2–3 weeks of focused study and mock coding
Success metricClear explanations, correct code, and thoughtful trade‑off discussion

Questions

Beginner

Explain the difference between HashMap and ConcurrentHashMap.

HashMap is not thread‑safe; concurrent reads and writes can corrupt its internal structure, leading to infinite loops or lost updates. ConcurrentHashMap partitions the map into segments, allowing multiple threads to read and write without global locking. It uses lock‑striping and non‑blocking algorithms for reads, providing higher throughput under contention. Interviewers expect you to discuss thread safety, performance trade‑offs, and when to choose each implementation.

AmazonGoogle

What is the Java Memory Model and why does it matter?

The Java Memory Model (JMM) defines how threads interact through memory, specifying visibility guarantees and ordering rules for reads/writes. It matters because without proper synchronization, a thread may see stale values or reorderings that break correctness. Understanding happens‑before relationships, volatile, and synchronized blocks shows you can write safe concurrent code and avoid subtle bugs like the double‑checked locking issue.

Microsoft

How does the Java synchronized keyword differ from a ReentrantLock?

synchronized is a built‑in monitor lock that is re‑entrant, automatically releases on block exit, and integrates with wait/notify. ReentrantLock offers explicit lock and unlock calls, supports fairness policies, tryLock with timeout, and condition objects for multiple wait‑sets. Interviewers want you to compare simplicity versus flexibility and discuss when explicit lock control is beneficial.

Microsoft

What are the trade‑offs between using ArrayList and LinkedList?

ArrayList offers O(1) random access and amortized O(1) append, but insert/remove in the middle requires shifting elements (O(n)). LinkedList provides O(1) insert/remove at ends and O(n) access because traversal is needed. Use ArrayList for read‑heavy workloads; LinkedList only when frequent middle insertions/deletions outweigh access cost. Interviewers look for performance reasoning.

Amazon

What is the purpose of the @FunctionalInterface annotation?

@FunctionalInterface signals that the interface is intended to have exactly one abstract method, enabling lambda expressions. The compiler enforces this constraint, preventing accidental addition of extra abstract methods. It improves readability and ensures compatibility with functional programming features introduced in Java 8.

Microsoft

Explain the principle of immutability and give an example of an immutable class.

Immutability means an object's state cannot change after construction, providing thread safety and simpler reasoning. A classic example is java.lang.String: all fields are final, and methods return new instances instead of modifying the original. To create a custom immutable class, declare fields final, provide no setters, and ensure defensive copies of mutable inputs.

Amazon

What is the difference between Callable and Runnable?

Runnable's run method returns void and cannot throw checked exceptions, while Callable's call method returns a result and can throw exceptions. Callable is used with ExecutorService to obtain Future objects representing asynchronous computation results. Interviewers look for understanding of task result handling and exception propagation.

Google

Intermediate

How does the JVM garbage collector work and which collector would you pick for a low‑latency service?

The JVM GC manages heap memory by tracing live objects and reclaiming unreachable ones. Different collectors (Serial, Parallel, CMS, G1, ZGC, Shenandoah) balance throughput versus pause time. For low‑latency services, a concurrent collector like G1 (with pause‑time goals) or ZGC/Shenandoah (sub‑millisecond pauses) is preferred. Explain why you’d tune heap size, pause‑time target, and consider region sizing to meet latency SLAs.

Netflix

Describe how Java streams handle parallel execution.

Parallel streams split the source data into sub‑streams, process each in a separate ForkJoinPool thread, and then combine results. The framework handles splitting, processing, and merging, but you must ensure operations are stateless and non‑interfering to avoid race conditions. Discuss the cost of thread creation, the need for proper collectors, and when parallelism actually improves performance.

Facebook

What are the differences between fail‑fast and fail‑safe iterators?

Fail‑fast iterators (e.g., those from HashMap) detect concurrent modification and throw ConcurrentModificationException, preventing undefined behavior. Fail‑safe iterators (e.g., from CopyOnWriteArrayList) operate on a snapshot, allowing modifications without exceptions but at higher memory cost. Interviewers look for awareness of concurrency implications and appropriate use cases for each type.

Oracle

Explain the concept of back‑pressure in Java reactive streams.

Back‑pressure allows a downstream subscriber to signal how many items it can handle, preventing the upstream publisher from overwhelming it. In Project Reactor or RxJava, this is expressed via request(n) calls. Proper back‑pressure handling ensures system stability under load. Interviewers expect you to describe how operators propagate demand and the consequences of ignoring it.

Google

How does the volatile keyword work and when is it insufficient?

volatile guarantees visibility of writes to other threads and prevents instruction reordering around the volatile access. However, it does not provide atomicity for compound actions (e.g., ++). For such cases, use synchronized or atomic classes. Interviewers expect you to discuss the happens‑before relationship and scenarios like double‑checked locking where volatile is essential.

Microsoft

Describe how the Java classloader hierarchy works.

The hierarchy starts with the bootstrap classloader loading core Java classes, followed by the extension classloader for JRE extensions, and the application classloader for classpath resources. Custom classloaders can delegate to parent loaders, following the parent‑first delegation model. Understanding this helps troubleshoot ClassNotFoundException and implement plugin architectures.

Amazon

How does the Java 8 default method affect interface evolution?

Default methods provide a concrete implementation within an interface, allowing new methods to be added without breaking existing implementations. This facilitates API evolution while preserving backward compatibility. Interviewers expect you to discuss potential diamond‑problem conflicts and how to resolve them with explicit overriding.

Oracle

When would you use a ScheduledExecutorService over Timer?

ScheduledExecutorService provides a thread pool, better exception handling, and flexible scheduling (fixed rate vs. fixed delay). Timer uses a single thread, so a task exception can terminate the timer. Use ScheduledExecutorService for robust, concurrent periodic tasks and when you need multiple concurrent timers.

Microsoft

What are the benefits and drawbacks of using Java records introduced in Java 14?

Records provide a concise syntax for immutable data carriers, automatically generating constructors, equals, hashCode, and toString. Benefits include reduced boilerplate and clear intent. Drawbacks are limited to shallow immutability, inability to extend other classes, and potential performance overhead if used in high‑frequency allocation scenarios. Interviewers assess understanding of when records simplify code versus when a full class is needed.

Google

Advanced

Explain the concept of lock striping and its benefit in ConcurrentHashMap.

Lock striping divides a map into multiple segments, each protected by its own lock. This reduces contention because threads accessing different segments can proceed concurrently. In ConcurrentHashMap, the number of stripes is typically a power of two, enabling efficient hashing to a segment. The benefit is higher throughput under high concurrency compared to a single global lock, while still providing thread safety.

Amazon

How does the Java 8 Optional class help avoid NullPointerException?

Optional encapsulates a possibly‑null value, forcing callers to explicitly handle the absent case via methods like orElse, ifPresent, or map. This eliminates implicit null checks and encourages a functional style, reducing NPE risk. Interviewers expect you to discuss how Optional improves API contracts and how misuse (e.g., wrapping null) defeats its purpose.

Google

When would you use a ThreadLocal and what are its pitfalls?

ThreadLocal provides per‑thread storage, useful for objects like SimpleDateFormat that are not thread‑safe or for request‑scoped data in web apps. Pitfalls include memory leaks if values are not cleared, especially in thread pools where threads live longer than the request. Also, overuse can hide data flow, making code harder to understand. Explain cleanup strategies and alternatives like scoped beans.

Netflix

What is the difference between @Transactional(propagation = REQUIRED) and REQUIRES_NEW?

REQUIRED joins an existing transaction if present; otherwise, it creates a new one. REQUIRES_NEW always suspends any existing transaction and starts a fresh one, committing or rolling back independently. This impacts atomicity and isolation; use REQUIRES_NEW for independent side‑effects like audit logging. Interviewers look for understanding of transaction boundaries and rollback behavior.

Oracle

What is the purpose of the java.lang.invoke package introduced in Java 7?

java.lang.invoke provides low‑level primitives for dynamic language support, including MethodHandle, CallSite, and invokedynamic. It enables more efficient runtime method dispatch, better JIT optimizations, and language‑agnostic bytecode. Candidates should explain how it replaces reflection for performance‑critical scenarios and its role in frameworks like LambdaMetafactory.

Oracle

When would you prefer using a CopyOnWriteArrayList?

CopyOnWriteArrayList is ideal for read‑heavy, infrequent‑write scenarios because each mutating operation creates a new copy of the underlying array, guaranteeing thread safety without locks. It provides snapshot iterators that never throw ConcurrentModificationException. However, it incurs high memory and CPU cost on writes, so use it for configuration lists or event listeners.

Netflix

Explain the difference between strong, soft, weak, and phantom references.

Strong references prevent GC. Soft references are cleared only under memory pressure, useful for caches. Weak references are cleared eagerly, enabling canonical mappings like WeakHashMap. Phantom references are enqueued after finalization, allowing cleanup of native resources. Interviewers want you to discuss use cases and how each reference type influences memory management.

Google

How does the Java 9 module system improve encapsulation?

The module system introduces module descriptors (module-info.java) that explicitly declare exported packages and required modules. It enforces strong encapsulation at compile and runtime, preventing accidental access to internal APIs. This reduces classpath conflicts and improves maintainability. Candidates should discuss how it impacts packaging and reflective access.

Oracle

Explain the concept of a memory leak in Java and how to detect it.

A memory leak occurs when objects remain reachable unintentionally, preventing GC reclamation. Common sources include static collections, ThreadLocal values not cleared, and listeners not deregistered. Detection involves profiling tools (VisualVM, YourKit) or heap dumps, analyzing retained sizes, and looking for unexpected references. Interviewers expect you to discuss mitigation strategies.

Amazon

Common mistakes

  • Confusing thread safety with immutability and forgetting to clear ThreadLocal values
  • Using synchronized blocks for high‑contention code instead of more scalable locks
  • Neglecting to discuss time‑complexity and trade‑offs when answering collection questions
  • Assuming volatile provides atomicity for compound operations
  • Over‑using CopyOnWriteArrayList without considering write cost

Study plan

  1. Week 1: Review core language features, collections API, and concurrency fundamentals with coding exercises.
  2. Week 2: Deep dive into JVM internals, garbage collectors, and performance tuning; run heap/GC profiling tools.
  3. Week 3: Practice design pattern questions and system‑design scenarios focusing on Java‑specific implementations.
  4. Week 4: Mock interviews covering coding, concurrency, and behavioral questions; refine explanations and trade‑off discussions.

FAQ

How many interview rounds are typical for a senior Java role?

Most companies use 4–5 rounds: an initial phone screen, a coding challenge, a deep‑dive Java session, a system‑design interview, and a cultural fit discussion.

Should I memorize Java API methods for the interview?

Focus on understanding key methods, their time‑complexities, and appropriate use cases rather than rote memorization. Interviewers value reasoning over recall.

Is it necessary to know Java 17 features for a 5‑year‑experience role?

Yes, being familiar with recent LTS releases (Java 11, 17) shows you stay current. Highlight features like records, sealed classes, and new garbage collectors.

What is the best way to demonstrate problem‑solving in a coding interview?

Explain the problem, outline a high‑level approach, write clean code, discuss edge cases, and analyze time/space complexity. Verbalize your thought process throughout.

How important are soft‑skill questions for a technical Java interview?

Very important; interviewers assess teamwork, communication, and how you handle ambiguity. Prepare concise stories that illustrate collaboration and conflict resolution.

Related

Ready for your next interview?

Download MiPrep AI. Load your resume and the job description. Show up ready.

Free tier · No credit card · macOS 14+ · Windows 10+

Free tier · No credit card · Runs on your Mac or Windows machine