Java Interview Preparation

Garbage Collection Interview Questions

Java memory, heap generations, garbage collectors, GC roots, and troubleshooting.

Garbage Collection Interview Focus

Java memory, heap generations, garbage collectors, GC roots, and troubleshooting.

Garbage Collection interview questions

Interview questions

20 matching

1. What is memory management in Java? Beginner

Java memory management is the JVM process of allocating memory for objects, method calls, class metadata, and runtime work, then releasing memory that is no longer needed. Objects and arrays are generally created on the heap, while each thread has its own stack for method frames, local values, and references. The garbage collector reclaims unreachable heap objects automatically. Developers still need to avoid unbounded caches, queues, and retained references because automatic cleanup cannot remove an object that is still reachable.

2. What is garbage collection in Java? Beginner

Garbage collection is the JVM process that finds heap objects no longer reachable by the application and reclaims their memory. For example, after `employee = null`, an object may become eligible for collection if no other live reference points to it. Collection timing is controlled by the JVM, so `System.gc()` is only a request, not a guarantee. Garbage collection mainly manages heap memory; native resources such as files and sockets still need explicit closing.

3. Why is garbage collection required in Java? Beginner

Garbage collection reduces the need for manual memory release. It helps reuse memory, improves memory safety, and prevents many errors such as double-free and invalid-memory-access bugs common in manual memory-management models. It does not prevent every memory problem. A static collection or an unbounded cache can retain objects that the application no longer needs, making them reachable and therefore impossible for the collector to reclaim.

4. What are the different memory areas in the JVM? Intermediate

The main JVM runtime areas are the heap, thread stacks, Metaspace, the program counter register, and the native method stack. The heap stores objects and arrays. Each thread stack stores method frames and local values. Metaspace stores class metadata. The program counter identifies the current instruction for a thread, while the native method stack supports native code. JVM implementations also use native memory and a code cache for JIT-compiled machine code.

5. What is the difference between heap memory and stack memory? Beginner

The heap is shared by application threads and generally stores objects and arrays. Its contents remain while objects are reachable and are managed by garbage collection. Each thread has a separate stack containing method frames, parameters, local primitive values, and object references. A stack frame is removed when its method returns. Excessive object retention can cause `OutOfMemoryError`, while very deep recursion can cause `StackOverflowError`.

6. What objects are stored in heap memory? Beginner

Class instances, arrays, strings, collections, wrapper objects, and objects created by frameworks are generally stored in heap memory. In `Employee employee = new Employee()`, the reference is used by the current stack frame, while the `Employee` object is on the heap. Instance fields are part of their containing object. JVM optimizations such as escape analysis may change the physical allocation, so heap and stack descriptions are useful concepts rather than absolute rules.

7. What information is stored in stack memory? Beginner

A thread stack contains frames for methods that are currently running. A frame can contain method parameters, local primitive values, local object references, intermediate calculation values, and return information. When the method returns, its frame is removed automatically. For `int result = first + second`, the parameters and local result belong to that invocation’s frame. The referenced object itself is generally stored in the heap, not inside the reference variable.

8. What is Metaspace, and how is it different from PermGen? Intermediate

Metaspace stores class-related metadata such as class definitions, method metadata, and field metadata. It replaced PermGen in Java 8. PermGen was a JVM-managed area commonly configured with `-XX:MaxPermSize`; Metaspace uses native memory and can be limited with `-XX:MaxMetaspaceSize`. Too many loaded classes, class-loader leaks, or continuously generated proxy classes can cause `OutOfMemoryError: Metaspace`.

9. How does the garbage collector identify unused objects? Intermediate

The collector starts from GC roots and follows references. GC roots include local variables in active stack frames, active threads, static fields, JNI references, and JVM-managed references. An object is live when it can be reached from a root. An isolated group of objects can reference one another and still be collected if no root can reach the group. This reachability model is why Java garbage collection is not simple reference counting.

10. What is the difference between strong, soft, weak and phantom references? Advanced

A strong reference is a normal reference and keeps an object alive. A `SoftReference` may be cleared under memory pressure and was traditionally used for memory-sensitive caches. A `WeakReference` does not prevent collection once stronger references disappear and is useful for weak mappings such as `WeakHashMap`. A `PhantomReference` always returns `null` from `get()` and works with a `ReferenceQueue` for advanced reclamation tracking. Modern caches usually prefer explicit size and expiry policies.

11. What are young generation, old generation and survivor spaces? Intermediate

Generational collectors use the observation that many new objects become unreachable quickly. New objects commonly begin in Eden in the young generation. Objects that survive a young collection may move between survivor spaces. Objects that remain alive for enough collections can be promoted to the old generation. The exact layout depends on the selected collector, but the model helps explain why young collections are frequent and why long-lived objects eventually create old-generation pressure.

12. What is the difference between minor GC, major GC and full GC? Intermediate

A minor GC mainly collects the young generation and processes Eden and survivor spaces. Major GC commonly refers to collection involving the old generation, but its meaning differs between collectors and tools. Full GC generally processes most or all of the heap and is usually more expensive. Repeated full GCs can indicate a small heap, high allocation rate, excessive retention, or a collector that cannot reclaim memory fast enough.

13. What is the purpose of Eden and Survivor spaces? Intermediate

Eden is the usual starting area for newly allocated objects. During a young collection, unreachable Eden objects are discarded and live objects are copied to a survivor space. The two survivor spaces alternate as source and destination, which allows live objects to be compacted without leaving many gaps. Objects that survive enough collections may be promoted to the old generation. Not every modern collector uses these spaces in exactly the same way.

14. What is object promotion in Java garbage collection? Intermediate

Object promotion is moving a surviving object from the young generation to the old generation. Promotion can happen after an object survives several young collections, reaches an age threshold, or cannot fit safely in survivor space. Promotion prevents long-lived objects from being processed repeatedly by every young collection. Excessive or premature promotion can fill the old generation quickly and lead to expensive old-generation or full collections.

15. What are the different garbage collectors available in Java? Intermediate

Common collectors include Serial GC, Parallel GC, G1 GC, ZGC, and Shenandoah, depending on the JDK distribution and version. Serial favours simplicity for small heaps. Parallel favours throughput. G1 balances throughput and pause targets for general server workloads. ZGC and Shenandoah focus on very low pauses by doing much of their work concurrently. Collector choice should be based on measured pause, throughput, heap size, and latency requirements.

16. What is the difference between Serial GC, Parallel GC, G1 GC and ZGC? Advanced

Serial GC uses a simple mostly single-threaded approach and suits small applications. Parallel GC uses multiple GC threads and is useful when throughput matters more than pause time. G1 divides the heap into regions and tries to meet pause-time goals while maintaining good throughput. ZGC performs most work concurrently and targets very short pauses, especially with large heaps. No collector is universally best; test the workload with production-like data.

17. What is a stop-the-world event in garbage collection? Intermediate

A stop-the-world event pauses application threads so the JVM can perform a phase that requires a stable object graph. The pause may be used to scan roots, copy or relocate objects, update references, or finish a collection phase. G1, ZGC, and Shenandoah perform substantial work concurrently, but they still have short pause phases. Long pauses can increase API latency, cause timeouts, and affect service-level objectives.

18. What causes an OutOfMemoryError in Java? Advanced

`OutOfMemoryError` means the JVM could not satisfy a memory allocation request. `Java heap space` can result from a small heap, large allocations, or a leak. `Metaspace` can result from class-loader or generated-class retention. `Unable to create native thread` can result from too many threads or OS limits. `Direct buffer memory` can result from excessive off-heap buffers. Diagnose the exact message with GC logs, heap dumps, native-memory data, and thread information before increasing limits.

19. What is a memory leak in Java, and how can it happen despite garbage collection? Advanced

A Java memory leak occurs when objects are no longer logically needed but remain reachable from a GC root. Common causes include static collections, unbounded caches and queues, listeners that are never removed, uncleared `ThreadLocal` values, and class-loader retention. The garbage collector cannot remove these objects because they are still reachable. Use bounded caches, cleanup callbacks, `ThreadLocal.remove()` in a `finally` block, try-with-resources, and heap-dump analysis to find the retaining reference.

20. How can you monitor, analyze and troubleshoot Java memory and garbage-collection issues? Advanced

Start by identifying heap growth, GC frequency, pause duration, CPU usage, or the exact `OutOfMemoryError` type. Enable modern GC logging with `-Xlog:gc*`, inspect heap and class histograms with `jcmd`, and capture a dump with `-XX:+HeapDumpOnOutOfMemoryError`. Analyze shallow and retained heap, dominator trees, and GC-root paths using tools such as Eclipse MAT or Java Mission Control. Compare post-GC live-set size before and after a fix, and use JFR to inspect allocation hot spots and pauses.

How to Prepare for Java Technical Interviews

Use this Java technical interview question bank to revise core concepts and practise explaining your decisions clearly. The questions cover Java fundamentals, object-oriented programming, collections, exceptions, multithreading, Spring Boot, Hibernate, databases, and other topics used in real software development interviews.

Start with the fundamentals, then move to scenario-based questions and advanced topics. Filter questions by difficulty to build confidence gradually. A strong answer should define the concept, explain why it matters, and include a practical example when appropriate.

Continue your preparation with the Java tutorials, or explore all interview preparation tracks for managerial and company-focused questions.