Sep 19, 2013

Job of new operator in java

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.
  1. If .class file is not loaded  then to load the .class file from hard disk to RAM and store into method memory area(mma).
  2. To allocate the memory for all non-static context and allocate the memory for all static member.
  3. Execute all static blocks.
  4. 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.
  5. Allocate memory for all non-static member of a class inside an object.
  6. If any non-static variable of a class which is not initialized, is initialized by its default value.
  7. Execute all non-static blocks into top to bottom order.
  8. Execute constructor.
  9. Write the hashcode into specified variable.
Note: If .class file is already loaded then step no 4 to 9 will be followed only.

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.