new keyword in Java:
The
new keyword in Java is used to create an instance of a class, also known as an object. It is used to allocate memory for an object and call the constructor of the class to initialize the object’s state. We can also use the new keyword to create an array object.
Here’s the basic syntax of using the new keyword:
"new" keyword
ClassName objectName = new ClassName();
Example 1: Creating an Object
creating an object using new keyword
public class Main{
void display() {
System.out.println("Invoking Method");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
Output
Invoking Method
In the above example, NewExample1 obj = new NewExample1(); creates an object of the NewExample1 class.
Example 2: Invoking a Constructor
Invoking a constructor
public class Main{
Main() {
System.out.println("Invoking Constructor");
}
public static void main(String[] args) {
Main obj = new Main();
}
}
Output
Invoking Constructor
In the above example, NewExample2 obj = new NewExample2(); creates an object of the NewExample2 class and invokes its constructor.
Example 3: Creating an Array Object
Creating new array object with 'new' keyword
public class Main{
static int arr[] = new int[3];
public static void main(String[] args) {
System.out.println("Array length: " + arr.length);
}
}
Output
Array length: 3
In the above example, int arr[] = new int[3]; creates an array object of integers with a length of 3.
These are the fundamental concepts of the new keyword in Java.