Java Reference
In-Depth Information
Initializing Arrays
An array can be initialized when it is declared. When initializing the array, the values
for the various indexed variables are enclosed in braces and separated with commas.
The expression with the braces is placed on the right-hand side of an assignment oper-
ator. For example:
int [] age = {2, 12, 1};
The array length (size) is automatically set to the number of values in the braces. So,
this initializing declaration is equivalent to the following statements:
int [] age = new int [3];
age[0] = 2;
age[1] = 12;
age[2] = 1;
You can also initialize array elements using a for loop. For example:
double [] reading = new double [100];
int index;
for (index = 0; index < reading.length; index++)
reading[index] = 42.0;
automatic
initialization
If you do not initialize the elements of an array, they will automatically be initialized
to a default value for the base type. The default values are the usual ones. For numeric
types the default value is the zero of the type. (For base type char the default value is the
nonprintable zeroth character (char)0 , not the space character.) For the type boolean
the default value is false . For class types, the default value is null . For example, if you
do not initialize an array of double s, each element of the array will be initialized to 0.0 .
Self-Test Exercises
1. In the array declaration
String[] word = new String[5];
what is
a. the array name?
b. the base type?
c. the length of the array?
d. the range of values an index accessing this array can have?
e. one of the indexed variables (or elements) of this array?
(continued)
Search WWH ::




Custom Search