skip to content

How do you create (instantiate) an array in Java with the new keyword, and what does the size argument do?

level: juniorimportance: must knowfreq 75%

answer

  1. new ElementType[length] → heap allocation
  2. Length fixed at creation, never resizable
  3. new int[0] legal; negative length → NegativeArraySizeException
  4. Slots default-initialized, then fill by index
  5. new int[3][4] vs jagged new int[3][]

basics

~20 s

Use new with the element type and a length, like new int[5]. This allocates an array of 5 ints on the heap. The length is fixed for the array's lifetime, and you fill the slots by index afterwards.

solid answer

~40 s

You instantiate an array with `new ElementType[length]`, e.g. `int[] a = new int[5];`. This allocates a heap object with `length` consecutive slots, each pre-filled with the type's default value. The length is determined at runtime (it can be any non-negative int expression, even a variable) but becomes fixed once the array exists — there is no resize. A negative length throws `NegativeArraySizeException`; a length of 0 is legal and yields an empty array. The reference (`a`) and the array object are separate: you can reassign `a` to a different, differently-sized array, but you cannot grow the existing one. For multi-dimensional arrays you can specify sizes per dimension, e.g. `new int[3][4]`, and Java also supports jagged arrays where only the first dimension is sized.

code

java · 6 lines
java
int n = 5;
int[] a = new int[n];   // runtime-sized, fixed-length
a[0] = 10;              // fill by index
// a = new int[10];     // 'resize' = new array + repoint
int[][] grid = new int[3][4]; // rectangular
int[][] jagged = new int[3][]; // jagged: rows sized later

go deeper

for a junior

Writes new int[n], knows length is fixed and slots start at defaults.

for a middle

Explains runtime-sized lengths, zero vs. negative length behavior, and that resizing means copy-into-a-new-array.

for a senior

Distinguishes reference vs. object lifetime, GC of abandoned arrays, and jagged vs. rectangular multi-dim creation.

for a principal

Reasons about length limits (Integer.MAX_VALUE/heap), why immutable length is a deliberate design (bounds-safety, contiguous layout), and the cost model behind ArrayList-style growth.

## The two steps: reference + object An array variable like `int[] a` is just a reference. To get actual storage you must **instantiate** an array object. The canonical way is the `new` operator: ```java int[] a = new int[5]; ``` This does two things: (1) allocates a heap object with 5 `int` slots, and (2) returns a reference to it, which is stored in `a`. ## What the length argument means The number inside the brackets is the **length** — how many elements the array holds. Key properties: - It can be any expression of type `int` (or narrower, promoted to int), including a variable computed at runtime: `new int[n]`. - **Length is fixed at creation.** An array can never be resized. "Growing" means allocating a new, larger array and copying (which is what `ArrayList` does internally). - **Zero length is legal:** `new int[0]` is a valid, usable empty array (common as a return value instead of `null`). - **Negative length is a runtime error:** it throws `NegativeArraySizeException`. - The maximum length is bounded by `Integer.MAX_VALUE` and available heap; very large requests throw `OutOfMemoryError`. ## Default element values Every slot is initialized to the type's default: `0` for numeric primitives, `false` for `boolean`, `''` for `char`, and `null` for any reference type. So `new int[5]` is `[0,0,0,0,0]` and `new String[5]` is five `null`s. (This is its own topic but is the reason `new` never leaves "garbage" in slots, unlike C.) ## Filling the array `new` only allocates; you assign values by index: ```java a[0] = 10; a[1] = 20; ``` Valid indices are `0` to `a.length - 1`; anything outside throws `ArrayIndexOutOfBoundsException`. ## Multi-dimensional creation Java arrays are arrays-of-arrays. You can size every dimension at once: ```java int[][] m = new int[3][4]; // 3 rows, each a new int[4] ``` Or size only the outer dimension and build **jagged** rows yourself: ```java int[][] j = new int[3][]; // 3 null rows j[0] = new int[2]; j[1] = new int[5]; ``` You may leave trailing dimensions unsized, but you cannot skip an earlier one: `new int[][4]` is illegal. ## Reference vs. object lifetime Reassigning the variable (`a = new int[10];`) abandons the old array (eligible for garbage collection) and points at a new one — this is the only way to 'change the size'. ## Bottom line `new T[n]` allocates a fixed-length, default-initialized array on the heap and returns a reference. Length is a runtime value but immutable thereafter; n must be non-negative.

  • What happens at runtime if you write new int[-1]?
    It throws NegativeArraySizeException at runtime. The length is only checked when the array is actually created, not at compile time.
  • How do you make a 2-D array where rows have different lengths?
    Create a jagged array: size only the first dimension (new int[3][]) and then assign each row its own array, e.g. j[0] = new int[2]; j[1] = new int[5];.

saying these in an interview costs you the question

  • Saying arrays can be resized after creation
  • Thinking length must be a compile-time constant
  • Believing negative or zero length both fail (only negative does)
  • Confusing new int[5] (5 slots) with new int[]{5} (one slot holding 5)

context