In this tutorial, we will learn about New Keyword in java . The new keyword in java is used to create an instance of class, also know as an object.
- In other words, it instantiates a class by allocating memory for a new object and returning a reference to that memory.
- The new keyword in java is used to allocate memory for the object on the heap, the memory space where objects are stored.
- New keyword in java allows dynamic allocation, it can be used to create array dynamically, which means the size of the array can be determined during runtime.
- New keyword in java returns a reference to the object that was created, this reference can be stored in a variable and it be used to access and interact with the object.
Features of new keyword
Some key features of the new keyword include:
- Object Creation : The new keyword is used to create instances of classes, allowing you to create multiple objects with different values.
- Memory Allocation : When the new keyword is used ,memory is allocated to store the object and its data.
- Constructor Invocation : The new keyword is followed by a constructor call, which initalizes the newly created object.
- Reference Assignment : The new keyword returns a reference to the newly created object,which can be assigned to a variable for further use.
Points To Remember of New Keyword
- The ‘new’ keyword is used to create an instance of a class or allocate memory for an object.
- It is followed by the name of the class and parentheses,which may contain arguments for the class’s constructor.
- When the ‘new’ keyword is used , it creates a new object in memory and returns a reference to that object.
- It is important to note that objects created using the ‘new’ keyword must be explicity deallocated by the programmer when they are no longer needed, using the ‘delete’ keyword in some some other languages.
Example of new keyword
public class DemoExample { void display() { System.out.println("Hello World"); } public static void main(String[] args) { DemoExample obj=new DemoExample(); obj.display(); } }
Output: Hello World