Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the JVM do when 'new' operator initializes the memory using the constructor?

RealEstate v = new RealEstate();

I have used this new keyword with RealEstate(). I know new allocates memory and initializes the memory using the RealEstate class constructor.

What is the JVM doing here?

like image 433
Shahab Khan Avatar asked Aug 20 '16 14:08

Shahab Khan


People also ask

Where does new operator in Java allocate memory?

The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.

Does new operator initialize the memory?

The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

How does a constructor allocate memory?

A constructor does not allocate memory for the class object its this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator.

How the memory is allocated for constructor in Java?

Default constructor is automatically called after an object is created. But in Java when we allocate memory using new operator i.e. classname obj = new classname(); the constructor is automatically invoked before new allocates memory to the class member's.


1 Answers

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.

like image 70
Raman Sahasi Avatar answered Dec 01 '22 19:12

Raman Sahasi