QuickTip: Java Basics: Stack and Heap

Posted on Monday, October 1, 2007


I was pair programming with an experienced Java Developer today and we again came up with the discussion of what goes on a stack and what goes on a heap. Though while coding application logic we are hardly concerned on what goes where but it definitely helps to know as it would help in better understanding of argument passing, polymorphism, threads, exceptions, and garbage collection.

Various pieces of Java program lie on one of the two places i.e. either on stack or on heap.

For a quick grasp read further

  • Instance variables and Objects lie on Heap. Remember this is where the state is maintained and when you get memory leaks this is where your profiler helps you to find the allocation of memory.
  • Local variables and methods lie on the Stack. So if we have a main method which calls the go() method which calls the gone() method then the stack from top to bottom would consist of




as soon as gone() has been processed it would be removed from the stack. Any corresponding local variables which are used in gone() would also be removed from the stack. Stack would have references to objects on the Heap.


Posted in: Java