Java 'new' Keyword Tutorial
new
The new keyword in Java is used to create new objects.
It instantiates a class by allocating memory for a new object and returning a reference to that memory.
The new keyword also invokes the object constructor.
Usage
The new keyword is typically used in the following way:
ClassName object = new ClassName(); - ClassName: Name of the class to be instantiated.
- object: Name of the reference variable.
- new: Keyword to instantiate the class.
- ClassName(): The constructor of the class.
Example
public class Student {
void study() { System.out.println("studying..."); }
public static void main(String args[]) {
Student s = new Student(); // creating object
s.study();
}
} Memory Allocation
When you create an object using the new keyword, memory is allocated in the Heap area.