Java – Initialize Array

You can initialize an array in Java by creating an array with a fixed size using the new keyword, or by supplying its initial values directly with an array initializer. The right form depends on whether you know the element values when the array is created.

Java Initialize Array

Declare and Initialize an Array in Java

Array declaration and array initialization are related but separate operations. A declaration creates an array variable. Initialization assigns an actual array object to that variable.

</>
Copy
int[] numbers;

The statement above declares a variable named numbers, but no array has been created yet. You can create the array later using new.

</>
Copy
int[] numbers;
numbers = new int[5];

You can also declare and initialize the array in a single statement.

</>
Copy
int[] numbers = new int[5];

The bracket placement int[] numbers is commonly preferred because it makes the array type clear, although Java also permits int numbers[].

Initialize Array using new keyword

You can initialize an array using new keyword and specifying the size of array.

Following is the syntax to initialize an array of specific datatype with new keyword and array size.

</>
Copy
datatype arrayName[] = new datatype[size];

where

  • datatype specifies the datatype of elements in array.
  • arrayName is the name given to array.
  • new keyword creates the array and allocates space in memory.
  • size specifies the number of elements in the array.

In the following example program, we will create an integer array of size five.

Java Program

</>
Copy
public class ArrayExample {

	public static void main(String[] args) {
		int numbers[] = new int[5];
	}
	
}

By default, the elements are initialized to default value of the datatype, which in this case of integer, it is zero. Let us check this statement by printing the elements of array.

Java Program

</>
Copy
public class ArrayExample {

	public static void main(String[] args) {
		int numbers[] = new int[5];
		
		for(int number: numbers)
			System.out.println(number);
	}
	
}

Output

0
0
0
0
0

Default Values Assigned to a Newly Initialized Java Array

When an array is created with new, Java automatically initializes every element with the default value for that element type. You do not get uninitialized array elements.

Array element typeDefault value
byte, short, int, long0
float, double0.0
char'\u0000'
booleanfalse
Reference types such as Stringnull

For example, the elements of a newly created String[] initially contain null.

</>
Copy
String[] names = new String[3];

for (String name : names) {
    System.out.println(name);
}
null
null
null

You can override these elements of array by assigning them with new values.

In the following program, we will initialize the array and assign values to its elements. You can access array elements using index.

Java Program

</>
Copy
public class ArrayExample {

	public static void main(String[] args) {
		int numbers[] = new int[5];
		
		numbers[0] = 42;
		numbers[1] = 25;
		numbers[2] = 17;
		numbers[3] = 63;
		numbers[4] = 90;
		
		for(int number: numbers)
			System.out.println(number);
	}
	
}

Output

42
25
17
63
90

Java array indexes start at 0. Therefore, an array of length 5 has valid indexes from 0 through 4. Its size is available through the length field.

</>
Copy
int[] numbers = new int[5];
System.out.println(numbers.length);
5

Initialize Array with List of Values

Instead of using new keyword, you can also initialize an array with values while declaring the array.

Following is the syntax of initializing an array with values.

</>
Copy
datatype arrayName[] = {element1, element2, element3, ...}

Let us write a Java program, that initializes an array with specified list of values.

Java Program

</>
Copy
public class ArrayExample {

	public static void main(String[] args) {
		int numbers[] = {42, 25, 17, 63, 90};
		
		for(int number: numbers)
			System.out.println(number);
	}
	
}

Output

42
25
17
63
90

When values are supplied in braces, Java determines the array length from the number of values. In this example, numbers.length is 5.

Initialize a Java Array with new and Explicit Values

You can also use new together with an array initializer. When explicit values are supplied, do not specify the array size separately.

</>
Copy
int[] numbers = new int[] {10, 20, 30};

This form is particularly useful when an array initializer appears in a context where the shorter brace-only form cannot be used by itself.

Initialize an Empty Array in Java

To create an array that contains no elements, initialize it with a length of zero. Its length is then 0.

</>
Copy
int[] numbers = new int[0];
String[] names = {};

System.out.println(numbers.length);
System.out.println(names.length);
0
0

A zero-length array is different from null. It is a valid array object; it simply has no elements.

Initialize a Java Array When the Size Is Not Known in Advance

A Java array has a fixed length after it is created. If you do not know how many elements will be needed, an ArrayList is usually more suitable because it can grow as values are added.

</>
Copy
import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();

        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        System.out.println(numbers);
    }
}
[10, 20, 30]

If an API later requires an array, a collection can be converted after the number of elements is known. Do not try to resize an existing Java array; creating a larger array creates a different array object.

Initialize an Array in a Java Constructor

An array stored in an object field can be initialized inside the class constructor. This is useful when the required array length is provided while creating the object.

</>
Copy
public class Scores {
    private int[] values;

    public Scores(int size) {
        values = new int[size];
    }

    public int getSize() {
        return values.length;
    }

    public static void main(String[] args) {
        Scores scores = new Scores(4);
        System.out.println(scores.getSize());
    }
}
4

Initialize and Return an Array from a Java Method

A Java method can create an array, initialize its elements, and return the array reference. The method return type must specify the corresponding array type.

</>
Copy
public class ReturnArrayExample {
    static int[] createNumbers() {
        return new int[] {10, 20, 30};
    }

    public static void main(String[] args) {
        int[] numbers = createNumbers();

        for (int number : numbers) {
            System.out.println(number);
        }
    }
}
10
20
30

Initialize a Two-Dimensional Array in Java

The same initialization ideas apply to multidimensional arrays. For a rectangular two-dimensional array, specify the number of rows and columns.

</>
Copy
int[][] matrix = new int[2][3];

System.out.println(matrix.length);
System.out.println(matrix[0].length);
2
3

You can initialize a two-dimensional array directly with values as well.

</>
Copy
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6}
};

Fixed Array Length After Java Array Initialization

The length chosen when an array is initialized cannot be changed. You can replace individual element values, but you cannot append an additional slot to the same array object.

</>
Copy
int[] numbers = {10, 20, 30};

numbers[1] = 50;
System.out.println(numbers[1]);
System.out.println(numbers.length);
50
3

If the number of values changes frequently, use a collection such as ArrayList instead of repeatedly creating new arrays.

Common Java Array Initialization Errors

Several common errors come from confusing an array’s length, its valid indexes, and the forms permitted for array initializers.

  • An array of length 5 has indexes 0 through 4, not 1 through 5.
  • The array length is fixed once the array has been created.
  • Brace-only initialization such as {1, 2, 3} is used as part of an array declaration; when assigning later, use new int[] {1, 2, 3}.
  • Creating new int[5] initializes five integer elements to 0; it does not leave them undefined.
  • Creating new String[5] creates five element slots initialized to null; it does not create five empty String objects.

Choosing a Java Array Initialization Form

RequirementTypical initialization
Known size, values assigned laterint[] a = new int[5];
Known values at declarationint[] a = {10, 20, 30};
Explicit array object with known valuesnew int[] {10, 20, 30}
No elementsnew int[0] or {}
Size changes while the program runsUse a collection such as ArrayList
Rows and columnsnew int[rows][columns]

Java Array Initialization Summary

Use new datatype[size] when you know the required array length but will assign values later. Use an array initializer such as {value1, value2, value3} when the values are already known. Java supplies default values for arrays created with new, and the array length remains fixed after creation. When the required number of elements is not known in advance, a dynamically sized collection such as ArrayList is generally a better fit.

In this Java Tutorial, we learned different ways of how to initialize an array with elements.