Initializing an Array – Declarations

Initializing an Array

Java provides the means to declare, construct, and explicitly initialize an array in one declaration statement:

Click here to view code image

element_type
[]
array_name
 = {
array_initialize_list
 };

This form of initialization applies to fields as well as to local arrays. The array_initialize_list is a comma-separated list of zero or more expressions. Such an array initializer results in the construction and initialization of the array.

Click here to view code image

int[] anIntArray = {13, 49, 267, 15, 215};

In the declaration statement above, the variable anIntArray is declared as a reference to an array of ints. The array initializer results in the construction of an array to hold five elements (equal to the length of the list of expressions in the block), where the first element is initialized to the value of the first expression (13), the second element to the value of the second expression (49), and so on.

Click here to view code image

Pizza[] pizzaOrder = { new Pizza(), new Pizza(), null };

In this declaration statement, the variable pizzaOrder is declared as a reference to an array of Pizza objects. The array initializer constructs an array to hold three elements. The initialization code sets the first two elements of the array to refer to two Pizza objects, while the last element is initialized to the null reference. The reference value of the array of Pizza objects is assigned to the reference pizzaOrder. Note also that this declaration statement actually creates three objects: the array object with three references and the two Pizza objects.

The expressions in the array_initialize_list are evaluated from left to right, and the array name obviously cannot occur in any of the expressions in the list. In the preceding examples, the array_initialize_list is terminated by the right curly bracket, }, of the block. The list can also be legally terminated by a comma. The following array has length 2, and not 3:

Click here to view code image

Topping[] pizzaToppings = { new Topping(“cheese”), new Topping(“tomato”), };

The declaration statement at (1) in the following code defines an array of four String objects, while the declaration statement at (2) shows that a String object is not the same as an array of char.

Click here to view code image // Array with 4 String objects:
String[] pets = {“crocodiles”, “elephants”, “crocophants”, “elediles”}; // (1)

// Array of 3 characters:
char[] charArray = {‘a’, ‘h’, ‘a’};    // (2) Not the same as “aha”