Java Tutorial Java Advanced Java Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

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

class_name object_name = new class_name();

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

5