What is a memory leak in Java and how do you prevent it?
Why Interviewers Ask This
Senior Java engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.
Answer
A memory leak in Java occurs when objects that are no longer needed remain referenced and cannot be garbage collected. Despite automatic GC, Java can still leak. Common causes: static fields holding collections that grow indefinitely, listeners/callbacks not deregistered after use, caches without eviction policies, long-lived objects holding references to short-lived ones (e.g., a static reference to an Activity in Android), and non-closed resources (streams, connections). Detection: heap dump analysis with Eclipse MAT or YourKit, monitoring heap growth with -verbose:gc. Prevention: use WeakReference for caches, remove listeners when done, use try-with-resources for I/O, and use profilers to catch leaks early in development.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Java answers easy to follow.
Previous
What is the Decorator design pattern in Java?
Next
What is the difference between Callable and Runnable in Java?