Before using the element of an array, it must have an initial value. In some programming languages do not set initial values default, and then when trying to access to an item an error occurs. In Java, all the variables, including the elements array have initial default value (default initial value). This default initial value is equal to 0 in numeric types or equivalent types (eg null for objects and false for boolean).
Of course, the initial values can be set explicitly. this can take place in different ways. A is possible through the use of literal expression for the elements of the array (array literal expression):
int[] myArray = {1, 2, 3, 4, 5, 6};
In this case, create and initialize the array simultaneously. Here’s how look in the memory array, then its values are initialized yet at the time of declaration:
In this syntax brackets replace the new operator and between has listed the initial value of the array, separated by commas. Their number determines its length.
Declaring and initializing the array – an example
Here’s another example of declaring and initializing immediately array:
String[] daysOfWeek = { “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday” };
In this case, the array is allocated with 7 elements of type String. Type String is reference type (object) and its values are stored in the dynamic memory.
Stack is allocated variable daysOfWeek, which points to stretch in dynamic memory that contains the elements of the array. Each of the 7 elements is an object of type string that itself points to another area of dynamic memory, which keeps its value.