Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Declaring an array variable does not create an array object. Allocate it with new, or create it with an initializer:

int[] values;
values = new int[5];              // five elements, initially 0

int[] scores;
scores = new int[] {10, 20, 30}; // three known values

This is invalid after a separate declaration: values = {10, 20, 30};. The brace-only shorthand is allowed only in the declaration itself.

These rules follow Java’s array model described in the official Java array tutorial and Java Language Specification, Chapter 10.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Declaration, allocation, and population are different steps

In this declaration:

int[] values;

values is a variable capable of referring to an array of int. No array object or element storage has been created. A local variable must be assigned before it is read:

int[] values;
System.out.println(values.length); // compilation error: values not initialized

By contrast, this both declares the variable and allocates an array:

int[] values = new int[3];

For a field, Java supplies a default null reference until your constructor or initializer assigns an array. A local variable has no usable default; it must be definitely assigned.

Allocate an empty array after declaration

Use this general form:

arrayVariable = new ElementType[length];
int[] numbers;
numbers = new int[5];

String[] names;
names = new String[3];

double[] prices;
prices = new double[10];

The length is fixed when the object is created and is available through the length field. A five-element array has indexes 0 through 4:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
System.out.println(numbers.length); // 5
numbers[0] = 12;
numbers[4] = 99;

Java cannot resize that array object. You can assign the variable to a different array, but that is replacement, not resizing.

Initialize with known values after declaration

When the values are known, use an array creation expression with an initializer:

int[] numbers;
numbers = new int[] {10, 20, 30};

The number of expressions determines the length. A trailing comma is also legal:

numbers = new int[] {10, 20, 30,};

The shorter form works only as part of a declaration:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
int[] numbers = {10, 20, 30}; // valid

int[] later;
later = {10, 20, 30};         // invalid Java syntax

After a declaration, new int[] tells the compiler what array object the initializer is creating.

Assign elements individually or with a loop

For a few values, assign by index after allocation:

int[] numbers;
numbers = new int[3];

numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

For patterned data, a loop is explicit and easy to debug:

int[] numbers;
numbers = new int[5];

for (int i = 0; i < numbers.length; i++) {
    numbers[i] = i * 10;
}

To inspect a one-dimensional result, use Arrays.toString:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import java.util.Arrays;

System.out.println(Arrays.toString(numbers));

Fill every element with one value

Arrays.fill expresses the intent directly:

import java.util.Arrays;

int[] numbers;
numbers = new int[5];
Arrays.fill(numbers, 7);

System.out.println(Arrays.toString(numbers)); // [7, 7, 7, 7, 7]

The range overload uses an exclusive upper bound:

Arrays.fill(numbers, 1, 4, 9); // indexes 1, 2, and 3 become 9

For reference arrays, fill stores the same reference in every slot; it does not clone an object:

Widget widget = new Widget();
Widget[] widgets = new Widget[3];
Arrays.fill(widgets, widget); // all three entries refer to widget

If Widget is mutable, changing it through one entry is observable through the others.

Generate values from indexes

A loop works for any generation rule:

int[] squares;
squares = new int[5];

for (int i = 0; i < squares.length; i++) {
    squares[i] = i * i;
}

For an index-based calculation, Java 8 and later also provide Arrays.setAll:

import java.util.Arrays;

int[] squares;
squares = new int[5];
Arrays.setAll(squares, i -> i * i);

System.out.println(Arrays.toString(squares)); // [0, 1, 4, 9, 16]

setAll is a compact, expressive alternative—not a guarantee of better performance. parallelSetAll can generate in parallel, but parallel overhead means it is not automatically advantageous for small arrays or cheap calculations.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Know the defaults after allocation

When no initializer is supplied, Java initializes each component according to its type:

int[] integers = new int[3];       // 0, 0, 0
double[] decimals = new double[3]; // 0.0, 0.0, 0.0
boolean[] flags = new boolean[3];  // false, false, false
char[] characters = new char[3];   // 'u0000', 'u0000', 'u0000'
String[] strings = new String[3];   // null, null, null

A reference array contains null references; allocating the array does not construct the referenced objects.

Initialize reference-type arrays correctly

String[] names;
names = new String[3];
names[0] = "Ada";
names[1] = "Grace";
names[2] = "Linus";

For objects, instantiate each element (or assign an existing object) separately:

Person[] people;
people = new Person[2];
people[0] = new Person("Ada");
people[1] = new Person("Grace");
Person[] people = new Person[2];
people[0].getName(); // NullPointerException: element 0 is still null

Initialize multidimensional and jagged arrays

A multidimensional array is an array whose components are themselves arrays:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
int[][] matrix;
matrix = new int[2][3];

int[][] other;
other = new int[][] {
    {1, 2, 3},
    {4, 5, 6}
};

Rows may have different lengths:

int[][] jagged;
jagged = new int[][] {
    {1, 2},
    {3, 4, 5},
    {6}
};

You can allocate only the outer array and create rows later:

int[][] matrix;
matrix = new int[3][];
matrix[0] = new int[2];
matrix[1] = new int[4];
matrix[2] = new int[1];

Until assigned, a row reference is null; accessing matrix[1][0] before allocating row 1 throws NullPointerException. Print nested arrays with Arrays.deepToString(matrix).

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Fields, constructors, static blocks, and final

An instance field can be declared first and initialized in a constructor:

class Example {
    private int[] values;

    Example() {
        values = new int[10];
    }
}

Use a static initializer for class-level setup:

class Example {
    private static int[] values;

    static {
        values = new int[10];
    }
}

A final array variable may be assigned once after declaration:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
final int[] numbers;
numbers = new int[3];
numbers[0] = 42;       // allowed: contents can change
numbers = new int[5]; // compilation error: reference already assigned

final protects the variable’s reference, not the array’s elements. A final instance field must be assigned on every constructor path, or in a declaration or instance initializer, according to Java’s definite-assignment rules.

Common errors and their fixes

Problem What happens Fix
values = {1, 2, 3}; Does not compile after a separate declaration. Write values = new int[] {1, 2, 3};.
Reading an unassigned local Compilation error. Allocate or assign it before use.
new int[-1] NegativeArraySizeException at runtime. Validate the length before creation.
Using index equal to length ArrayIndexOutOfBoundsException. Use indexes from 0 through length - 1.
Writing through a null reference NullPointerException. Assign an array object first.
Calling a method on an uninitialized object element NullPointerException. Create or assign that element.
Filling mutable objects with one instance All entries alias the same object. Create separate objects when independent state is required.

When an array is the wrong container

Use an array when its fixed length, primitive storage, predictable layout, or API interoperability is useful. If the number of elements changes over time, prefer ArrayList or another collection rather than repeatedly allocating and copying arrays. Collections are not a universal replacement: fixed-size data and low-level representations still suit arrays.

Quick reference

Situation Syntax
Allocate a known number of slots values = new int[size];
Assign known literals later values = new int[] {1, 2, 3};
Set selected elements values[index] = value;
Generate by rule for (...) { ... } or Arrays.setAll(values, ...)
Use one value everywhere Arrays.fill(values, value);
Print a one-dimensional array Arrays.toString(values)
Print nested arrays Arrays.deepToString(matrix)
Need changing length ArrayList<T> or another collection

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.