menu

Monday, January 12, 2015

Where Is The Java Primitives Stored In Memory ?

 Introduction:

     Today we'll mention about the memory usage of primitives. There is two different usage of primitive types in java in terms of memory usage. One is using the primitives as local variables in an instance or static method, the other is using them as class variables defining directly at the class level.

 Primitives as Local Variables:

     As we know all Threads in java has their own stack and when we call a java method (not a native method) a new frame is added to the current thread's frame by the JVM. All the local variables including the method parameters and local variables defined in the method are added to this new frame on to the stack. For an instance method there will also be an objectref as local variable at position 0 which is an implicit this pointer pointing to the current instance of the class. 
Note: We may later talk about the method call architecture in detail including invokevirtual (for instance method call), invokestatic (for static method call), invokespecial (for constructor call (to be able to call the super's constructor first)) and invokeinterface (to call an instance method given a reference to the interface- to see difference of invokeinterface look for this link.). The fastest ones of course invokestatic and invokespecial since they use static binding instead of dynamc binding.
Anyway since we use thread's stack frame for all the local variables all the pritimives defined here will be holded in the stack and will be discarded at the end of the method call directly.

 Primitives as Class Variables:

     Since the objects do not have their own stack, the primitives defined as class variables will not be on any stack, instead they will be on the heap under the reference of the class that includes the variable whenever a new instance created on that class.

 Example:

public class TestPrimitiveMemory {
     
     private int i; // no need to initialize since its automatically done

     public void m1() {
          int y = 0; // need to initialize
     }
}

TestPrimitiveMemory  tpm = new TestPrimitiveMemory ();// at this line int i with a value of 0 will be added on the heap.
tpm.m1();// m1 is put on to the current thread's stack frame and int y primitive variable is created on the stack.

 Conclusion:

     We pointed out where the primitive variables are holded on the memory depending on the place it is defined. Primitives created as local variables are created on stack while primitives created as class variables are created on heap.