The knowledge sharing zone -

Stack and heap memory variables

This tutorial contains the details about where JVM stores the different types of variables. How to decide which all are Stack and Heap memory variable in our java program.

Understanding of stack and heap makes it easier to understand topics like argument passing, polymorphism, threads, exceptions garbage collection.

The various pieces (eg. methods, variables, and objects) of Java programs live in one of two places in memory: the stack or the heap.

  1. Instance variables and objects live on the heap.
  2. 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 Collar { }
3. class Dog {
4.   Collar c; // instance variable
5.   String name; // instance variable
7.   public static void main(String [] args) {
9.     Dog d; // local variable: d
10.    d = new Dog();
11.    d.go(d);
12.  }
13.  void go(Dog dog) { // local variable: dog
14.    c = new Collar();
15.    dog.setName("Aiko");
16.  }
17.  void setName(String dogName) { // local var: dogName
18.    name = dogName;
19.    // do more stuff
20.  }
21. }

Below figure shows the state of the stack and the heap once the program reaches line 19.

Keypoints about stack and heap memory variables are:

  • Line 7—main() is placed on the stack.
  • Line 9—reference variable d is created on the stack, but there's no Dog object yet.
  • Line 10—a new Dog 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 dog parameter as a local variable.
  • Line 14—a new Collar object is created on the heap, and assigned to Dog's instance variable.
  • Line 17—setName() is added to the stack, with the dogName 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 Dog 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 dogName disappears too, although the String object it referred to is still on the heap.



You would also like to read:

What is type casting in java
Instance initialization and static block in java

Comments :

Name :
Email :
Comment :
Verify Text :
capch image, refresh page if not loaded somehow