CKTIS / Java
new — creating objects and arrays
new — creating objects and arrays: The new operator creates a class instance through a class instance creation expression or creates an array; for a class it allocates the object and then runs the selected constructor.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
newThe new operator creates a class instance through a class instance creation expression or creates an array; for a class it allocates the object and then runs the selected constructor.
Use a constructor to establish invariants, the diamond for type-argument inference, and a factory when an operation name better explains creation.
new cannot instantiate an abstract type, interface, or primitive; a constructor may throw, and allocation can end with OutOfMemoryError.
An array has default values and fixed length; an anonymous class can implement an interface, and a non-static inner class needs an enclosing instance.
The first new creates a StringBuilder whose constructor starts with A, so append yields A21; the second creates an array containing 2 and 3 whose sum prints 5.
Examples
public class Main {
public static void main(String[] args) {
StringBuilder text = new StringBuilder("A").append(21);
int[] values = new int[] {2, 3};
System.out.println(text);
System.out.println(values[0] + values[1]);
}
}
Result
A21 5
The first new creates a StringBuilder whose constructor starts with A, so append yields A21; the second creates an array containing 2 and 3 whose sum prints 5.