The new keyword and object creation
The new keyword is used to create an object (instantiate a class). It allocates memory on the heap and returns a reference to the newly created object.
Syntax:
ClassName objectName = new ClassName(arguments);Steps:
- Memory is allocated for the object.
- The appropriate constructor is called.
- A reference to the object is returned.
Example:
Student s = new Student("Alice", 20);Multiple objects:
Point p1 = new Point(0, 0);Point p2 = new Point(5, 10);Anonymous objects: Created without storing a reference.
new Point(3, 4).display(); // method called directly, object eligible for GC afterArray creation:
int[] numbers = new int[10]; // array of primitivesPoint[] points = new Point[5]; // array of references (null initially)points[0] = new Point(1, 2); // assign object to array element