Wednesday, September 14, 2016

How are Java objects stored in memory?

Very frequent question on java that how java objects are stored in memory.

Ans: 

In Java, all objects are dynamically allocated on Heap.
In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on heap.

For example, following program fails in compilation. Compiler gives error “Error here because t is not initialed”.

class Test {
    // class contents
    void show() {
        System.out.println("Test::show() called");
    }
}

public class Main {
    public static void main(String[] args) {
        Test t;
        t.show(); // Error here because t is not initialed
    }
}

Allocating memory using new() makes above program work.

class Test {
    // class contents
    void show() {
        System.out.println("Test::show() called");
    }
}
 
public class Main {
    public static void main(String[] args) {
        Test t = new Test(); //all objects are dynamically allocated
        t.show(); // No error
    }
}

in java basically there are different section where jvm allocate memory either loading time of class or run time.

1.) class area or method area -> here static data member gets memory at loading time of class.
2.) heap area -> here object get memory and it initialize all instance data member
at run time of class.
3.) stack area -> here local variable gets memory .

No comments: