Page 410 - Introduction to Programming with Java: A Problem Solving Approach
P. 410

                376 Chapter 10 Arrays and ArrayLists
Comparing the above statement to the previous temperatures code fragment, you can see that it is the same in terms of functionality but different in terms of structure. Key differences: (1) It’s one line, rather than five lines. (2) There’s no new operator. (3) There’s no array-size value. With no array-size value, how do you think the compiler knows the size of the array? The size of the array is dictated by the number of values in the element-values list. In the above example, there are five values in the initializer list, so the compiler creates an array with five elements.
We presented two solutions for assigning values to a temperatures array. Which is better—the five-line code fragment or the one-line array initializer? We prefer the array initializer solution because it’s simpler. But remember that you can use the array initializer technique only if you know the assigned values when you first declare the array. For the temperatures example, we do know the assigned values when we first declare the array—we initialize each temperature to 98.6, the normal human body temperature in degrees Fahrenheit. You should limit your use of array initializers to situations where the number of assigned values is reasonably small. For the temperatures example, the number of assigned values is reasonably small—it’s five. If you need to keep track of a hundred temperatures, it would be legal to use the array initializer solu- tion, but it would be cumbersome:
double[] temperatures =
{
}
98.6, 98.6, 98.6, 98.6, 98.6, 98.6, 98.6, 98.6, 98.6, 98.6,
<repeat above line eight times>
98.6, 98.6, 98.6, 98.6, 98.6, 98.6, 98.6, 98.6, 98.6, 98.6
         Apago PDF Enhancer
Default Values
You now know how to initialize an array’s elements explicitly with an array initializer. But what do an array’s elements get by default if you don’t use an array initializer? An array is an object, and an array’s ele- ments are the instance variables for an array object. As such, an array’s elements get default values when the array is created, the same as any other instance variables get default values. Here are the default values for array elements:
 Array Element’s Type
 Default Value
 integer
 0
 floating point
 0.0
 boolean
 false
 reference
 null
 So what are the default values for the elements in the arrays below?
double[] rainfall = new double[365];
String[] colors = new String[5];
The rainfall array gets 0.0 for each of its 365 elements. The colors array gets null for each of its 5 elements.









































































   408   409   410   411   412