Information Technology Reference
In-Depth Information
Initializing an Array
Array elements are always initialized. If they are not explicitly initialized, the system will auto-
matically initialize them to default values.
Automatic Initialization
When any type of array is created, each of the elements is automatically initialized to the
default value for the type. The default values for the predefined types are 0 for integer types,
0.0 for floating point types, false for Booleans, and null for reference types.
For example, the following code creates an array and initializes its four elements to the
value 0 . Figure 14-6 illustrates the layout in memory.
int[] intArr = new int[4];
Figure 14-6. Automatic initialization of a one-dimensional array
Explicit Initialization of One-Dimensional Arrays
For a one-dimensional array, you can set explicit initial values by including an initialization list
immediately after the array creation expression of an array instantiation.
￿
The initialization values must be separated by commas and enclosed in a set of curly braces.
￿
Notice, however, that nothing separates the array creation expression and the initializa-
tion list. That is, there is no equals sign or other connecting operator.
For example, the following code creates an array and initializes its four elements to the val-
ues between the curly braces. Figure 14-7 illustrates the layout in memory.
Initialization list
int[] intArr = new int[4] { 10, 20, 30, 40 };
No connecting operator
Search WWH ::




Custom Search