Java Tutorial Java Advanced Java References

Java new Keyword



The Java new keyword is used to create an instance of the class. It invokes the class constructor to create the object and allocate the memory at runtime.

Syntax

className objectName = new className();

Example:

In the example below, the new keyword is used to create an object of the given class called MyClass. The object is further used to call the class method display().

public class MyClass {
  public void display() {
    System.out.println("Hello World!.");
  }

  public static void main(String[] args) {
    MyClass obj = new MyClass();
    obj.display();
  }
}

The output of the above code will be:

Hello World!.

Example:

In the example below, the new keyword is used to create new instance of the class called MyClass, which invokes the class constructor to create the object.

public class MyClass {
  public MyClass() {
    System.out.println("Hello World!.");
  }

  public static void main(String[] args) {
    MyClass obj = new MyClass();
  }
}

The output of the above code will be:

Hello World!.

❮ Java Keywords