Java Reference
In-Depth Information
Once an array of primitive data types is declared and constructed, the stored
value of each array element will be initialized to zero; however, reference data
types such as Strings are not initialized to SPACEBAR blanks or an empty string.
You must populate String arrays explicitly.
To reference a single element, the code should include the index number in
brackets.
System.out.println(answer[5]);
In the above example, answer is the name of the array. The sixth element of the
array will display during run time because array index numbers begin with zero.
Using Array Index Numbers
Arrays assign an index number, or subscript, to each element of
the array, allowing the program and the programmer to access
individual values when necessary. Index numbers are always inte-
gers; they begin with zero and progress sequentially by whole
numbers to the end of the array. Thus, to reference the sixth array
element, you would use the integer, 5, in brackets.
You also can use assignment statements to explicitly place values within
arrays, just as you do with single variables.
temperature[3] = 78;
After it has been executed, the fourth element of the array named temperature
will hold the value 78.
Alternately, you can declare, construct, and assign values using one
statement, as in the following example.
boolean[] results= { true, false, true, true, false };
Java provides this shortcut syntax for creating and initializing an array. The
length of this boolean array is determined by the number of values provided
between the braces, { and }.
Array elements can be used anywhere a variable can be used.
overtime = (hours[6] - 40) * rate[6] * 1.5
In the above example, overtime is calculated by taking the seventh element of the
hours array, subtracting 40, multiplying it by the seventh element of the rate
array, and then finally multiplying that product by 1.5 for time-and-a-half pay.
Search WWH ::




Custom Search