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
trueNotes
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
In the tutorial
- Classes and objects — What classes and objects are in Java: fields, methods, the new operator, default values and object references.