Concept Explanation
Imagine you are working in a giant Distribution Center.
- The Stack (Your Desk): This is for data you are using right now. When you call a method, you clear a small space on your desk (a Stack Frame) for its variables. When the method finishes, you clear the desk completely. It's fast, but space is limited.
- The Heap (The Warehouse): This is for big, long-term items (Objects). If you create a
new Car(), it's too big for your desk, so it gets stored in the warehouse. You just keep a small Note (a Reference) on your desk telling you where in the warehouse the car is.
Key Differences
| Feature | Stack (Desk) | Heap (Warehouse) |
|---|---|---|
| Speed | Extremely Fast | Slower |
| Items | Primitive variables & References | Objects and Arrays |
| Lifetime | Temporary (lives only during method) | Long-term (lives until cleaned up) |
| Error | StackOverflowError | OutOfMemoryError |
Common Mistakes
- Infinite Recursion: Calling a method within itself forever fills up the "Desk" (Stack), causing a
StackOverflowError. - Memory Leaks: Keeping "Notes" (References) to objects in the warehouse that you don't need anymore. Because you still have the note, the warehouse won't throw the item away.
Practice Exercises
- The Stack Overflow: Write a method that calls itself with no stop condition. Run it and see how long it takes to crash.
- Pass by Value: Research why Java is always "Pass by Value." If you pass an object to a method, are you passing the "Car" or the "Note" (Reference)?
- The Null Test: If you set a reference variable to
null, what happens to the "Note" on your desk? What happens to the object in the "Warehouse"?