The <code>new</code> Keyword in Java
new creates a new object or array. It allocates memory, calls the constructor, and returns a reference. For every non-primitive value in Java, new is either in your code or hidden behind a factory method like List.of(...).
Creating objects
User u = new User("Alice", 30);
var list = new ArrayList<String>(); // var + diamond = tight syntax
var map = new HashMap<String, Integer>();
The diamond operator (Java 7+)
List<String> old = new ArrayList<String>(); // redundant type argument
List<String> mod = new ArrayList<>(); // inferred from the left-hand side
Arrays
int[] a = new int[10]; // all zeros
int[] b = new int[]{1, 2, 3}; // with initialiser
int[] c = {1, 2, 3}; // short form β only at declaration
int[][] matrix = new int[4][4]; // 2-D array
Anonymous classes
Runnable r = new Runnable() {
@Override public void run() { System.out.println("hi"); }
};
// Modern: lambda when the type is a functional interface
Runnable r = () -> System.out.println("hi");
Factories often replace new
List.of("a", "b", "c"); // no 'new'
Map.of("a", 1, "b", 2);
Path.of("src", "main");
Instant.now();
Optional.of(value);
Prefer factories: they can return an immutable instance, an interned object, or the most appropriate implementation type.
new isn't the only way
- Primitives aren't created with
newβ they're values. - String literals (
"hello") come from the string pool, notnew String("hello"). - Enum constants are created once at class load.
- Singletons intentionally avoid
newafter the first call.
Common mistakes
new String("literal")β creates an unnecessary second object. Just use"literal".new Boolean(true)β deprecated since Java 9. UseBoolean.TRUE.- Raw types β
new ArrayList()without type argument is legal but defeats generics. Add<>. - Allocating in a hot loop β garbage collector pressure. Reuse or use a pool where it matters (rare in modern JVMs).
Related
Pillar: Java keywords. See also constructors, classes.