BCA / B.Tech 9 min read

The `new` Operator in Java

What is the `new` Operator in Java?

The new operator is a fundamental keyword in Java used to create instances of objects. When you use new, you are dynamically allocating memory for a new object on the heap (a region of computer memory used for dynamic allocation).

The Process of Object Creation with `new`:

When you write a line like MyClass obj = new MyClass();, several things happen in sequence:

  1. Memory Allocation: The `new` operator allocates enough memory on the heap to store all the instance variables and other internal data for an object of `MyClass`.
  2. Constructor Call: After allocating memory, the operator calls the class's constructor. The constructor is a special method that initializes the newly created object, setting its initial state by assigning values to its instance variables.
  3. Return a Reference: Finally, the operator returns a reference (or memory address) to the newly created and initialized object. This reference is then assigned to the variable (obj in this case), allowing you to interact with the object.

Examples:

Creating a simple object:


// StringBuilder is a class in Java
// sb is a reference variable that will hold the address of the object
StringBuilder sb = new StringBuilder("Hello"); 
        

Creating an array object:


// `new` allocates memory for an array that can hold 10 integers
int[] numbers = new int[10]; 
        

In essence, the `new` operator is the key to bringing a class blueprint to life as a tangible object in memory.