Shahab Khan Shahab Khan - 1 year ago 74
Java Question

What Jvm does when new operator initialize the memory using the constructor?

RealEstate v=new RealEstate();

I have used this
keyword with
. I know
allocates memory and initializes the memory using constructor

But my question is:What Jvm does when new operator initialize the memory using the constructor?

rD. rD.
Answer Source

new operator doesn't actually uses the help from constructor to allocate memory. It has nothing to do with constructor. Basically Java's version of malloc is new.

new operator:

  • allocates memory for an object
  • invokes object constructor
  • returns reference to that memory

Constructor is executed separately to perform any operations during initialization, like allocating values to objects and variables. If no Constructor is defined, then compiler will create default constructor and will allocate default values:

The following chart summarizes the default values for several data types. source

Data Type   Default Value (for fields)
byte            0
short           0
int             0
long            0L
float           0.0f
double          0.0d
char            '\u0000'
String          null
any object      null
boolean         false

So, new operator only allocates memory and returns reference to that memory.

See the documentation:

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download