Java - Array Explicit Initialization


You can initialize elements of an array explicitly.

The initial values for elements are separated by a comma and enclosed in braces {}.

// Initialize the array at the time of declaration
int[] empId = {1, 2, 3, 4, 5};

The code above creates an array of int of length 5, and initializes its elements to 1, 2, 3, 4, and 5.

The length of an array is the same as the number of values specified in the array initialization list.

A comma may follow the last value in initialization list.

int[] empId = {1, 2, 3, 4, 5, }; // A comma after the last value 5 is valid.

Alternatively, you can initialize the elements of an array as shown:

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

It is valid to create an empty array by using an empty initialization list.

int[] emptyNumList = { };

For a reference type array, you can specify the list of objects in the initialization list.

// Create a String array with two Strings "Tom" and ""
String[] name = {new String("Tom"), new String("")};

// You can also use String literals
String[] names = {"Tom", ""};

// Create an Account array with two Account objects
Account[] ac = new Account[]{new Account(1), new Account(2)};