Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › How Java Runs — JDK, JRE, JVM & Your First Program

At a beginner level, what is the difference between the stack and the heap?

Level I · BeginnerHow Java Runs — JDK, JRE, JVM & Your First Program
Short answer

The stack holds each method call's frame -- its local variables and the bookkeeping to return -- and unwinds automatically as methods return.

Explanation

The heap is the shared region where objects created with `new` live; variables on the stack hold references (pointers) to those heap objects. Primitives and references sit on the stack; the actual objects sit on the heap and are cleaned up later by the garbage collector. (The deep mechanics come later in the JVM Internals phase.)

Common mistakes
  • Saying objects live on the stack — objects live on the heap; the stack holds frames, primitives and references.
  • Thinking the stack is shared between threads; each thread has its own.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for How Java Runs — JDK, JRE, JVM & Your First Program.

Practise free

More on How Java Runs — JDK, JRE, JVM & Your First Program