Skip to main content

11. Stack and Heap Memories

 

Stack and Heap Memories

  • Instance variables and objects live on the heap.
  • Local variables live on the stack.
1.  class A {
2.  }
3.  
4.  class JetPlane {
5.      A a; // instance variable: a
6.      String name; // instance variable: name
7.  
8.      public static void main(String[] args) {
9.          JetPlane plane; // local variable: plane
10.         plane = new JetPlane();
11.         plane.go(plane);
12.     }
13. 
14.     void fly(JetPlane pla) { // local variable: plane
15.        a = new A();
16.         pla.setName("Rafel");
17.     }
18. 
19.     void setName(String planeName) { // local variable: planeName
20.         name = planeName;
21.     }
22. }
  • Line 8: main() is placed on the stack.
  • Line 9: reference variable plane is created on the stack, but there's no JetPlane object yet.
  • Line 10: a new JetPlane object is created and is assigned to the plane reference variable.
  • Line 11: a copy of the reference variable plane is passed to the fly() method.
  • Line 14: the fly() method is placed on the stack, with the plane parameter as a local variable.
  • Line 15: a new A object is created on the heap, and assigned to JetPlane's instance variable.
  • Line 19: setName() is added to the stack, with the planeName parameter as its local variable.
  • Line 20: the name instance variable now also refers to the String object.
  • The two different local variables (pla and plane) refers to the same JetPlane object.
  • One local variable (planeName) and one instance variable (name) both refers to the same String Rafel.
  • After Line 20 completes, setName() completes and is removed from the stack. At this point the local variable planeName disappears too, although the String object it referred to is still on the heap.


Prev Next

Comments