Saturday, June 25, 2011

How different variables stored in java - on Heap and stack

  • Instance variables and objects live on the heap.
  • Local variables live on the stack.

Let’s take a look at a Java program, and how its various pieces are created and map into the stack and the heap:

1. class Cub{ }
3. class Lion {
4.   Maine c; // instance variable
5.   String name; // instance variable
7.  public static void main(String [] args) {
9.    Lion d; // local variable: d
10.   d = new Lion();
11.   d.go(d);
12.  }
13.  void go(Lion lion) { // local variable: Lion
14.    c = new Cub();
15.    lion.setName("Bakait");
16.  }
17.   void setName(String LionName) { // local var: LionName
18.    name = LionName;
19.    // do more stuff
20.   }
21. }

  This is how the variables and methods get placed in the stack and heap during execution of the above piece of code.
  • Line 7—main() is placed on the stack.
  • Line 9—reference variable d is created on the stack, but there’s no Lion object yet.
  • Line 10—a new Lion object is created and is assigned to the d reference variable.
  • Line 11—a copy of the reference variable d is passed to the go() method.
  • Line 13—the go() method is placed on the stack, with the Lion parameter as a local variable.
  • Line 14—a new Maine object is created on the heap, and assigned to Lion’s instance variable.
  • Line 17—setName() is added to the stack, with the LionName parameter as its local variable.
  • Line 18—the name instance variable now also refers to the String object.
  • Notice that two different local variables refer to the same Lion object.
  • Notice that one local variable and one instance variable both refer to the same String Aiko.
  • After Line 19 completes, setName() completes and is removed from the stack. At this point the local variable LionName disappears too, although the String object it referred to is still on the heap.

No comments:

Post a Comment