SteelReed

Search

Search posts, questions…

Java CoreQuestion 2 / 43

Junior

What is the difference between stack and heap? When do StackOverflowError and OutOfMemoryError occur?

Short answer

Each thread has its own stack holding the local variables of the running method, cleared when the method ends. The heap is shared, holds every object, and is cleaned by the GC (garbage collector).

no references leftcalls too deepheap full, still referencedThread 1: stack framevariable oOrder object on heapThread 2: stack frameGC reclaimsStackOverflowErrorOutOfMemoryError

3 points to say:

  1. Local variables live on the stack, objects on the heap.
  2. Recursion too deep: StackOverflowError.
  3. Heap full of still-referenced objects: OutOfMemoryError.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.