← Back to libraryQuestion 4 of 273
JavaIntermediate

Heap vs Stack Memory

📖 Detailed Explanation:

Stack memory is used for thread execution and stores local variables and method call frames. It is fast, follows LIFO (Last-In-First-Out), and is thread-specific. Heap memory is a large shared pool used for dynamic object allocation. All objects are stored in the heap, and all threads share this memory. Stack is automatically freed when methods return; heap requires garbage collection.

🌍 Real-World Example:

Stack: A stack of plates in a restaurant—you take from the top and put back on top. Heap: A bulk storage warehouse—items are randomly placed and retrieved.

🎯 Scenario-Based Interview Question:

You have a method that calls itself recursively 10,000 times. After many calls, you get an error. Which memory is full, and how does it differ from a memory leak?