Java Reference
In-Depth Information
All elements of an array are stored contiguously in memory. In case of a reference type array, the array elements
store the references of the objects. Those references in the elements are stored contiguously, not the objects they are
referring to. The objects are stored on heap and their locations are, typically, not contiguous.
Explicit Array Initialization
You can initialize elements of an array explicitly when you declare the array or when you create the array object using
the new operator. 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};
This code creates an array of int of length 5, and initializes its elements to 1 , 2 , 3 , 4 , and 5 . Note that you do not
specify the length of an array when you specify the array initialization list at the time of the array declaration. The
length of the array is the same as the number of values specified in the array initialization list. Here, the length of the
empId array will be 5, because you passed 5 values in the initialization list { 1 , 2 , 3 , 4 , 5} .
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};
Note that you cannot specify the length of an array if you specify the array initialization list. The length of the
array is the same as the number of values specified in the initialization list.
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. The following snippet of
code illustrates array initialization for String and Account types. Assume that the Account class exists and it has a
constructor, which takes an account number as an argument.
// Create a String array with two Strings "Sara" and "Truman"
String[] name = {new String("Sara"), new String("Truman")};
// You can also use String literals
String[] names = {"Sara", "Truman"};
// Create an Account array with two Account objects
Account[] ac = new Account[]{new Account(1), new Account(2)};
When you use an initialization list to initialize the elements of an array, you cannot specify the length of the array.
the length of the array is set to the number of values in the initialization list.
Tip
 
 
Search WWH ::




Custom Search