Top 50 Java Interview Questions & Answers (2026 Advanced Guide)

Tech Quiz App Icon

Java remains the bedrock of enterprise software, high-performance financial systems, and massive scalable backends. However, the Java interview landscape has shifted dramatically. In 2026, interviewers don't just want you to know the syntax; they expect a deep understanding of JVM internals, memory management, Virtual Threads, and modern Spring Boot architectures.

Whether you are aiming for a FAANG company or a high-growth startup, we have curated the ultimate, highly-technical list of the Top 50 Java Interview Questions. Let's dive into the depths of modern Java!

⚙️ Part 1: JVM Internals, GC & Memory

1. Explain the ClassLoader hierarchy in the JVM.

The JVM uses three main ClassLoaders. 1) Bootstrap ClassLoader: Loads core Java APIs (rt.jar). Written in native code. 2) Extension ClassLoader: Loads classes from the ext directory. 3) Application (System) ClassLoader: Loads application-specific classes from the classpath. They follow the Delegation Principle—a child asks its parent to load a class before attempting to load it itself.

2. What is the Generational Hypothesis in Garbage Collection?

It is the observation that "most objects die young." Therefore, the JVM Heap is divided into the Young Generation (Eden and Survivor spaces) and the Old (Tenured) Generation. The GC runs fast, minor collections frequently in the Young generation to quickly clear short-lived objects, saving CPU cycles.

3. How do modern GCs (G1GC and ZGC) minimize "stop-the-world" pauses?

G1GC divides the heap into regions and prioritizes sweeping regions with the most garbage, aiming to meet user-defined pause-time targets. ZGC (Z Garbage Collector) performs expensive work (like object relocation) concurrently with application threads, keeping max pause times strictly under 1 millisecond, regardless of heap size.

4. What causes an OutOfMemoryError: Metaspace?

Metaspace replaced the PermGen space in Java 8. It stores class metadata (class definitions, methods, bytecode). An OOM in Metaspace happens if an application dynamically loads too many classes at runtime without unloading them, common in massive Spring Boot apps or apps heavily using dynamic proxy generation (CGLIB).

5. Explain "Escape Analysis" and Stack Allocation.

Escape Analysis is a JVM optimization. If the JIT compiler determines that a newly created object will never "escape" the local method (i.e., it is not returned or assigned to a global variable), the JVM will allocate that object entirely on the Thread Stack rather than the Heap. This completely bypasses Garbage Collection overhead.

6. What is JIT Compilation? Explain C1 vs C2.

The Just-In-Time (JIT) compiler compiles Java bytecode into native machine code at runtime for heavily used methods ("hot spots"). C1 (Client compiler) compiles quickly but with less optimization. C2 (Server compiler) takes longer to compile but aggressively optimizes the code. Java uses Tiered Compilation, starting with C1 and upgrading "hot" code to C2.

7. How does the JVM handle String pooling?

Because Strings are immutable, the JVM maintains a String Pool in the heap. If you create a string via a literal ("Hello"), the JVM checks the pool. If it exists, it returns the reference; if not, it adds it. The intern() method forces a dynamically created String (using new) into the pool.

8. Explain Lock Coarsening and Lock Elimination.

Lock Elimination: If the JIT compiler detects that a synchronized block can only ever be accessed by a single thread (via Escape Analysis), it completely removes the lock. Lock Coarsening: If the JVM sees multiple synchronized blocks using the same lock back-to-back, it merges them into a single larger lock to reduce synchronization overhead.

9. What is a Memory Leak in Java if it has a Garbage Collector?

A memory leak in Java occurs when objects are no longer needed by the application but are still actively referenced by living objects (e.g., adding objects to a static List or Map and never removing them). Because the GC sees an active reference, it cannot delete them, eventually leading to an OutOfMemoryError.

10. Heap vs Stack Memory in Java?

Heap: Stores all objects and classes. It is shared across all threads. Stack: Every thread has its own private Stack. It stores local variables, method calls, and primitive types. When a method finishes, its stack frame is popped instantly. Stack access is significantly faster than Heap access.

FREE RESOURCE TechQuiz App Features

Ready to test your Java skills? 🚀

Practice these exact JVM questions and thousands more on the TechQuiz app. Track your progress and crush your FAANG interview.

Get it on Google Play

⚡ Part 2: Multithreading & Virtual Threads

11. What are Virtual Threads (Project Loom) in Java 21?

Virtual threads are lightweight threads managed by the JVM, not the OS. Unlike Platform Threads (which are heavy and limited to a few thousand), you can spawn millions of Virtual Threads. When a Virtual Thread hits a blocking I/O operation (like a DB call), it instantly yields its underlying carrier OS thread to another Virtual Thread, skyrocketing throughput.

12. Explain the Java Memory Model and `happens-before`.

The JMM dictates how threads interact through memory. Due to CPU caching, one thread might update a variable, but another thread might not see it immediately. The happens-before relationship is a guarantee that memory writes made by one specific statement are perfectly visible to another specific statement (e.g., unlocking a monitor happens-before another thread locks the same monitor).

13. What is the `volatile` keyword? Does it guarantee atomicity?

volatile ensures memory visibility. It forces a thread to read/write a variable directly from Main Memory, bypassing CPU caches. However, it does not guarantee atomicity. Operations like count++ are actually three steps (read, increment, write) and will still cause race conditions with volatile. Use AtomicInteger for atomicity.

14. Difference between `synchronized` and `ReentrantLock`?

synchronized is intrinsic, simpler, and automatically releases the lock even if an exception occurs. ReentrantLock (from java.util.concurrent) offers advanced features: checking if a lock is available (tryLock()), fairness policies (longest waiting thread gets the lock next), and the ability to interrupt a thread waiting for a lock.

15. How does `ConcurrentHashMap` achieve high performance?

Instead of locking the entire Map (like HashTable), it uses highly granular locking at the Node/Bucket level (via Compare-And-Swap (CAS) operations and synchronized blocks). This allows multiple threads to read and write to different parts of the map simultaneously without blocking each other.

16. What is a `CompletableFuture`?

Introduced in Java 8, it represents a future result of an asynchronous computation. Unlike standard Future, it allows you to chain multiple async operations non-blocking using callbacks (like thenApply, thenCompose), handle exceptions cleanly, and combine multiple async results effortlessly.

17. Explain ThreadLocal and its potential risks.

ThreadLocal allows you to create variables that can only be read and written by the same thread. It's useful for storing thread-specific context (like a user transaction ID). The risk: if used in a web server with Thread Pools, the thread is reused. If you forget to call threadLocal.remove(), data leaks into the next user's request.

18. What is a CountDownLatch vs a CyclicBarrier?

CountDownLatch: Allows one or more threads to wait until a set of operations performed by other threads completes (cannot be reused once the count reaches 0). CyclicBarrier: Allows a set of threads to all wait for each other to reach a common barrier point before continuing (can be reset and reused).

19. How do you detect and prevent a Deadlock in Java?

A deadlock happens when Thread 1 holds Lock A waiting for B, and Thread 2 holds Lock B waiting for A. Detection: Take a thread dump using jstack or JVisualVM to see blocked threads. Prevention: Always acquire locks in the exact same consistent order globally, or use tryLock() with a timeout.

20. Explain the Fork/Join Framework.

Designed for parallel execution of divide-and-conquer tasks. It uses a Work-Stealing algorithm: if a worker thread has finished its own queue of tasks, it can "steal" pending tasks from the end of another busy thread's queue, perfectly balancing CPU load across all cores.

TechQuiz App Download

👇 Dominate System Design & Multithreading 👇

Join thousands of engineers using TechQuiz to master concurrency and land jobs at top tier tech companies.

Get it on Google Play

📦 Part 3: Collections & Modern Java

21. How does `HashMap` handle collisions internally (Java 8+)?

When multiple keys hash to the same bucket (collision), they are stored in a LinkedList. However, in Java 8, if a single bucket reaches 8 elements (and the total map capacity is >= 64), that LinkedList dynamically converts into a Red-Black Tree (Treeification), reducing search time from O(n) to O(log n).

22. What are `Records` in Java?

Introduced in Java 14, record is a special class type designed exclusively to act as an immutable data carrier. It automatically generates the constructor, getters, toString(), equals(), and hashCode() methods, completely eliminating boilerplate code for DTOs.

23. Explain Pattern Matching for `switch` (Java 21).

You can now pass objects into a switch statement and match against their types instantly (e.g., case String s -> System.out.println(s.length());). It completely removes the need for multiple instanceof checks and ugly casts.

24. Difference between `fail-fast` and `fail-safe` iterators?

Fail-fast iterators (like ArrayList) throw a ConcurrentModificationException if the collection is structurally modified (item added/removed) while iterating. Fail-safe iterators (like ConcurrentHashMap, CopyOnWriteArrayList) operate on a clone of the collection and will never throw this exception.

25. What are Sealed Classes?

Introduced in Java 17, sealed classes allow you to strictly control which specific classes are allowed to extend or implement them using the permits keyword. This enables exhaustive pattern matching and domain modeling by ensuring all possible subclasses are known at compile time.

26. How do Streams work internally?

Streams rely on a Spliterator to traverse data. The operations are split into Intermediate (lazy operations like map/filter that just build a pipeline of instructions) and Terminal (like collect/count, which trigger the actual execution). Because of laziness, multiple operations are fused into a single pass over the data.

27. Difference between `map()` and `flatMap()` in Streams?

map() transforms one object into exactly one another object (1-to-1). flatMap() is used when each element transforms into a Collection of elements. It flattens all those internal collections into a single, massive continuous stream of elements (1-to-Many).

28. Explain the impact of `hashCode()` and `equals()` contract violations.

If two objects are equals(), they MUST have the same hashCode(). If you override equals() but forget to override hashCode(), you will never be able to find your object inside a HashSet or HashMap. The map will compute the wrong bucket and assume the object doesn't exist.

29. What is the purpose of the `Optional` class?

It is a container object used to represent the possible absence of a value, forcing the developer to actively handle the null case, preventing NullPointerException. However, it should only be used as a return type. Never use it as a class field or method argument, as it adds unnecessary memory overhead.

30. How does `CopyOnWriteArrayList` work?

It is a thread-safe List. Every time a thread modifies it (add/set/remove), it creates a brand new, massive clone of the underlying array. It is incredibly expensive for writes but absolutely perfect and lightning-fast for scenarios with massive amounts of Reads and very rare Writes.

🏗️ Part 4: Core Java & Advanced OOP Concepts

31. Abstract Class vs Interface (Java 8+)?

Since Java 8, interfaces can have implementation code via default and static methods. The main difference now is state: Abstract classes can hold instance variables (state) and have constructors. Interfaces cannot hold state (variables are implicitly public static final) and cannot be instantiated.

32. How do you create a truly immutable class?

1. Declare the class as final.
2. Make all fields private final.
3. Provide no setters.
4. If fields contain mutable objects (like a Date or List), perform a Deep Copy in the constructor, and return a clone in the getter to prevent external modification.

33. What is Type Erasure in Java Generics?

To maintain backward compatibility with older Java versions, the compiler entirely removes (erases) all Generic type information during compilation. List<String> simply becomes a raw List of Object in the bytecode. This means you cannot check instanceof List<String> at runtime.

34. How does Java resolve Multiple Inheritance conflicts with Interfaces?

If a class implements two interfaces that both have the exact same default method signature, it creates the Diamond Problem. The Java compiler will refuse to compile the code. The class MUST override the conflicting method and manually specify which interface's method it wants to use: InterfaceA.super.methodName();.

35. Checked vs Unchecked Exceptions?

Checked Exceptions (extend Exception) are checked at compile-time (like IOException). The compiler forces you to try/catch them or declare them in the method signature. Unchecked Exceptions (extend RuntimeException) represent programming bugs (like NullPointerException) and do not need to be explicitly declared or caught.

36. Explain "Pass by Value" in Java.

Java is strictly Pass by Value. When you pass an object to a method, Java passes a copy of the memory reference. The method can modify the object's internal data (because both references point to the same heap location), but if the method reassigns the reference to a completely new object, the original caller's reference remains unchanged.

37. What is Reflection, and what are its implications?

Reflection allows Java code to inspect and dynamically execute classes, methods, and private fields at runtime (heavily used by Spring for Dependency Injection). It is incredibly powerful but comes with severe performance overhead and disables certain JIT compiler optimizations.

38. How does Serialization work, and why is `transient` used?

Serialization converts an object into a byte stream to be sent over a network or saved to disk. If an object contains a sensitive field (like a password) or an object that cannot be serialized (like a Thread connection), you mark that field as transient, and the JVM will completely ignore it during serialization.

39. What are Java Modules (Project Jigsaw)?

Introduced in Java 9, modules allow developers to explicitly define which packages are exposed to other modules and which are hidden internally using module-info.java. This brought true strong encapsulation to Java and allowed developers to strip out unneeded parts of the JDK, creating dramatically smaller runtime images.

40. Explain the use of the `final` keyword.

On a Variable: Value cannot be reassigned once set (constant).
On a Method: It cannot be overridden by any subclasses.
On a Class: The class cannot be inherited/extended by any other class (like the String class).

🚀 Part 5: Spring Boot & Microservices

41. How does `@SpringBootApplication` trigger auto-configuration?

It is a combination of three annotations. @Configuration, @ComponentScan, and critically, @EnableAutoConfiguration. This scans the classpath jars. If it sees Tomcat, it configures a web server. If it sees a Postgres driver, it automatically creates a DataSource bean without you writing a single line of XML.

42. Difference between `@Component`, `@Service`, and `@Repository`?

@Component is the generic base annotation. @Service is a specialized version to demarcate business logic layers. @Repository is specialized for Data Access Objects (DAOs) and provides the added benefit of translating low-level database exceptions (like SQL errors) into Spring’s unified DataAccessException hierarchy.

43. What is Inversion of Control (IoC) and Dependency Injection (DI)?

IoC transfers the control of object creation away from the programmer to the Spring Framework (the IoC Container). DI is the pattern used to implement it: instead of a class instantiating its dependencies using new, the framework injects them (via constructor or setter), enabling massive decoupling and easy testing.

44. How does Spring Boot handle concurrent HTTP requests?

Spring Boot uses an embedded Tomcat server by default. Tomcat maintains a Thread Pool (default max 200). When an HTTP request hits, Tomcat assigns it to an idle worker thread. If all 200 threads are busy (blocking on DB calls), new requests are queued, and eventually rejected, unless you switch to WebFlux (reactive) or Java 21 Virtual Threads.

45. Explain JPA vs Hibernate, and the "N+1 selects" problem.

JPA is just the specification (interfaces). Hibernate is the actual underlying implementation that executes the SQL. The N+1 Problem happens when querying a parent entity, and the ORM executes 1 query for the parent list, and N additional queries to fetch the children of each parent. Fix it using JOIN FETCH or EntityGraphs.

46. How do you implement resilience in Microservices?

If Service A calls Service B, and B goes down, A will hang and eventually crash too (cascading failure). You use a Circuit Breaker (like Resilience4J). After a certain number of failures, it "opens" the circuit, instantly failing fast to prevent hanging. You also implement Retries and Rate Limiting to protect fragile services.

47. Explain the `@Transactional` annotation.

It ensures Atomicity. If a method executes 3 DB writes and the 3rd one fails, Spring uses AOP proxies to automatically trigger a DB rollback, undoing the first 2 writes to maintain data integrity. Propagation levels (like REQUIRES_NEW) control whether a method joins an existing transaction or creates an entirely new one.

48. How do you secure a REST API using JWT and Spring Security?

You configure a custom SecurityFilterChain. When a user logs in, issue a signed JSON Web Token (JWT). For subsequent requests, the client passes the JWT in the Authorization header. You write a custom Filter to intercept the request, cryptographically verify the JWT signature, extract the roles, and set the security context.

49. What is the difference between `@Controller` and `@RestController`?

@Controller is for traditional web apps returning HTML views (JSP/Thymeleaf). @RestController is a convenience annotation that combines @Controller and @ResponseBody. It ensures that the returned objects are automatically serialized directly into JSON/XML bypassing the view resolver.

50. How would you design a Rate Limiter for a Java-based API?

For a single server, you can use the Token Bucket algorithm (Guava RateLimiter) or Resilience4J. For distributed microservices, you must use a centralized store like Redis running a Lua script to evaluate the limit atomically across all servers, protecting your backend from DDoS attacks or runaway clients.


TechQuiz App Preview

Master Your Next Java Interview ☕

Reading theory is great, but executing under pressure requires practice. Test your knowledge, build muscle memory, and land that Senior Java Developer role using the Tech Quiz app.

👇 DOWNLOAD FOR FREE 👇

Get it on Google Play

Comments

Popular posts from this blog