The new keyword in java

The new keyword in java is used to create instance of a class.

The new keyword in java

The new keyword in java

In this section you will learn about new keyword in java. The new keyword is used to create a instance of a class. The new keyword allocates a space in the memory and initialize the object.

Syntax :  

A ob1 = new A(12,56);
Shape ob2 = new Shape(ob,32,98);

First line creates the object of A class and second class create an object of shape class.

Each of these statement has three parts, they are as follows :

  1. ob1 and ob2 are all variable declaration associated with an object type, this is called declaration.
  2. Creating  an object by new keyword this is nothing but intanstiation.
  3. The new keyword is followed by a call to constructors and which initializes the new object this is nothing but initialization.

The new operator instantiate a class by allocating memory for a new object and returning a reference to that memory. The new operator also invoke object constructor. The new operator returns a reference to the object it created. This reference assigned to the variable of the appropriate type like:
A ob = new A();

While using  new  keyword some points to be remember :

  • The  new  keyword is followed by a class name and passing values to the constructors.
  • Number of arguments to the constructors must be the same in signature of constructor.
  • The type of variable on the left side of assignment  is compatible with the class being instantiated.