What actually happens when an object of a  class is created  in Java ?

What actually happens when an object of a class is created in Java ?

Table of contents

No heading

No headings in the article.

class Student{
    public static void main(String [] args){
        Student s1; // Reference s1 is created in the stack
        s1 = new Studnet(); // Mermory is allocated to s1 in heap
    }
}
  • The first statement states that reference (s1) is created in the stack. Here reference means to address in the memory.

  • The Second statement states that class Student is loaded in the Main Memory and memory is allocated to its member or object (s1) in the Heap, and along with that all the data members are initialized by the JVM with their corresponding default value simultaneously.

  • JVM reserves the portion of heap memory for the object and the size of heap memory which is reserved is dependent on the size of the object.

  • The JVM maps out this segment in the Heap to represent all of the attributes of the object being stored.

  • A reference (address in Heap) to the object is kept by the JVM and stored in a table that allows the JVM to keep track of all the objects that have been allocated on the Heap.

  • The JVM uses these references to access the objects later (when the program accesses the object).