Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

new

Creates a new object or array and calls the constructor.

Available since: Java 1.0

Syntax

new ClassName(arguments)

Examples

Creating objects and arrays:

void main() {
    var sb = new StringBuilder("hi");
    int[] numbers = new int[3];
    var list = new ArrayList<String>();
    list.add("x");
    IO.println(sb + " " + numbers.length + " " + list);
}

Output:

hi 3 [x]

Each new makes a separate object:

record Point(int x, int y) {}
 
void main() {
    var a = new Point(1, 2);
    var b = new Point(1, 2);
    IO.println(a == b);
    IO.println(a.equals(b));
}

Output:

false
true

Notes

Many objects are created without new, through static factory methods: List.of(), LocalDate.of(), Path.of(), Integer.valueOf(). String literals do not need new: new String("x") creates a needless copy.

See also

  • this — A reference to the current object — the one whose method or constructor is running.
  • class — Declares a class — a description of objects: their fields and methods.
  • var — Declares a local variable whose type the compiler infers from the value.

In the tutorial

  • Classes and objects — What classes and objects are in Java: fields, methods, the new operator, default values and object references.

Thanks for reading!

Donate to the site — we work hard for you.