What does new operator do?
new operator in java is used for creating the object of the class. new operator instantiates the class and allocates memory to the object. As an object is instantiated all non-static member of the class are activated and ready to be used. It is the well known working of new operator, I want to tell you what happens in the memory when an object is created in the memory i.e. job of new operator or responsibilities of new operator in java programming.
We will discuss step by step jobs of new operator. First i want to tell you how we create an object?
class_name <reference variable> = new class_name();
Here, <reference variable> is the variable of specified class and it stores the hashcode(address of object where it has been created) returned by the new operator. hashcode is in the form of hexadecimal code.
Now we will discuss job of new operator.
- If .class file is not loaded then to load the .class file from hard disk to RAM and store into method memory area(mma).
- To allocate the memory for all non-static context and allocate the memory for all static member.
- Execute all static blocks.
- Create the context or segment for an object of class into heap memory area and generate a unique id that is known as hashcode. Non technically we call it reference id or unique id.
- Allocate memory for all non-static member of a class inside an object.
- If any non-static variable of a class which is not initialized, is initialized by its default value.
- Execute all non-static blocks into top to bottom order.
- Execute constructor.
- Write the hashcode into specified variable.
Use of new operator in java programming is very broad. new operator is responsible for many tasks which we have discussed above. It completes the discussion of What actually new operator does in java. For more queries please visit internal mechanism of object.