Memory allocation is done before first line of constructor execution or after constructor execution - Java

480 Views Asked by At
Student student = new Student();

In the above code, we have created one Student class object, in that is JVM allocate the memory before the first line of constructor execution or after the constructor execution, Even after the parent classes?

2

There are 2 best solutions below

2
On

When a variable of class type is declared only a reference is created. Memory is allocated (in the heap) only when said variable is initialized with the new() keyword. You should be able to check the memory read/write operations with NetBeans profiler if you're using Netbeans, though I guess most IDE include a similar tool. The memory is allocated as first thing inside the constructor rather than last.

0
On

In short, it is allocated before the constructor.

Your code can be also written like this:

Student student;
student = new Student();

This means that when the variable student is declared, it is declared as an empty reference in the first line. When that happens, the memory allocated a space for student, declaring it as a variable of type Student as a reference until initialized into a usable variable.