☕ Java Beginner

What is the difference between stack and heap memory in Java?

Answer

The stack stores method call frames — each thread has its own stack. Local variables, method parameters, and return addresses are stored here. Stack memory is automatically managed (LIFO) and is very fast. Objects cannot be stored on the stack (only references to objects). The heap is shared among all threads and is where all objects and their instance fields are allocated. It is managed by the garbage collector. Heap access is slower than stack. A StackOverflowError occurs when the stack runs out of space (usually from infinite recursion). An OutOfMemoryError occurs when the heap is full and GC cannot free enough memory.