Tuesday, December 11, 2012

Where are variables stored in Java, Stack or Heap?


A primitive variable “holds” directly his value itself. Examples of a primitive variable :  int i, long l;

A reference variable “holds” the reference (4 bytes on 32-bit JVMs, 8 bytes on 64-bit JVMs) who refers to an object. Examples of a reference variable : Student s, Date d;

local variable : a variable created in a method, the method parameter included.
instance variable : a variable that belongs to the instance of an object
class variable :  a variable that belongs to the class

public static void main(String args[]){
int a = 1;
Integer b = 2 ;
Student c = new Student();
c.setName(“kewei”);
}

public class Student {
int age = 27;
Date birthday = new Date();
String name;

public void setName(String nameParam) {
this.name = nameParam;
}
// ...
}

a is a primitive variable.
b is a reference variable (not object) who refers to an Integer object.
c is a reference variable (not object) who refers to a Student object.
age is a primitive variable.
birthday is a reference variable (not object) who refers to a Date object.

So where are all these variables stored, on the heap or on the stack? The answer is simple.

All local variables (primitive and reference variables) are stored on the stack. Everything else are stored on the heap.

All objects are stored on the heap.
All instance variables (primitive and reference variables) are stored on the heap too, since they are part of the object.
All class variables are stored on the heap too.

Stack is created for each individual thread. In this example, there is only one stack (the stack calls main() method). For multithread programs, there will be multiple stacks.

Analyze:
a, b are stored on the stack because they are local variables. c will also be stored on the stack because it is a local variable (at the same time, it is a reference variable). However, the student object that c refers to is stored on the heap. age is stored on the heap, because it is part of that student object. birthday is stored on the heap for the same reason (birthday is an instance variable, part of that student object). The date object that birthday refers to is also stored on the heap. name is also stored on the heap. nameParam is stored on the stack, because it is a local variable.

2 comments:

  1. what is instance variable and how many instance variable present in example?

    ReplyDelete
  2. Its wrong. All class variables and instance variables are stored in Permanent Generation memory not in a heap. Dont be confuse. Google it.

    ReplyDelete