Page 411 - Introduction to Programming with Java: A Problem Solving Approach
P. 411
10.4 Array length Property and Partially Filled Arrays 377 10.4 Array length Property and Partially Filled Arrays
As illustrated earlier, when working with an array, it’s common to step through each element in the array. In doing so, you need to know the size of the array and/or the number of filled elements in the array. In this section, we discuss how to obtain the size of an array and how to keep track of the number of filled elements in an array.
Array length Property
Suppose you have a five-element colors array that’s been initialized like this:
String[] colors = {"blue", "gray", "lime", "teal", "yellow"};
Here’s how to print such an array:
for (int i=0; i<5; i++)
hard-coded array size
{
}
System.out.println(colors[i]);
That works OK, but suppose you have several other color-related loops in your code, each of them using
i<5. If you modify your program to accommodate more colors, and change the five-element array to a
ten-element array, you’d have to change all occurrences of i<5 to i<10. To avoid such maintenance work, Apago PDF Enhancer
wouldn’t it be nice to replace i<5 or i<10 with something generic, like i array’s size? You can do that by using the color array’s length property. Every array object contains a length property that stores the number of elements in the array. The length property is called a “property,” but it’s actually just an instance variable with public and final modifiers. The public modifier says that length is directly accessible without need of an accessor method. The final modifier makes length a named constant; so you can’t update it. Here’s how the length property can be used:
for (int i=0; i<colors.length; i++)
{
}
System.out.println(colors[i]);
ArraylengthPropertyVersusString lengthMethod
Remember where else you’ve seen the word length in the Java language? The String class provides a length method to retrieve the number of characters in a string. Remember that String’s length is a method, so you must use trailing parentheses when calling it. On the other hand, an array’s length is a constant, so you don’t use trailing parentheses when accessing it. Figure 10.4’s SpeedDialList2 program il- lustrates these concepts. Note that phoneNum.length() uses parentheses when checking for the length of the phoneNum string as part of input validation. And note that phoneList.length does not use parentheses when checking the number of elements in the phoneList array to make sure that there’s room for another phone number.
If you’re like us, you might have a hard time remembering when to use parentheses and when not to. Try using the mnemonic acronym ANSY, which stands for Arrays No, Strings Yes. “Arrays No” means that
number of elements in the array