Page 406 - Introduction to Programming with Java: A Problem Solving Approach
P. 406
372 Chapter 10 Arrays and ArrayLists
phoneList
8167412000
2024561111
7852963232
8008675309
0035318842133
first speed-dial phone number
last speed-dial phone number
Figure 10.1 Example array—five-element array for holding a list of speed-dial phone numbers
element’s index. Figure 10.2 shows how to access the individual elements within the phoneList array. The first element’s index is 0, so you access the first element with phoneList[0]. Why is the first element’s in- dex 0 instead of 1? The index is a measure of how far you are from the beginning of the array. If you’re right at the beginning, the distance from the beginning is 0. So the first element uses 0 for its index value.
index
0 1 2 3 4
phoneList
how to access each element
phoneList[0]
8167412000
2024561111
Apago
7852963232
8008675309
0035318842133
PDF Enhancer
phoneList[1]
⎪ phoneList[2] ⎬
⎪
⎪ phoneList[4] ⎭
5 elements
⎫ ⎪
phoneList[3]
Figure 10.2 Accessing elements in a phoneList array
Beginning programmers often think that the last index in an array is equal to the number of elements in the array. For example, a beginning programmer might think that the last index in the phoneList array equals 5 because the phoneList array has 5 elements. Not so. The first index is 0, and the last index is 4. Try to remember this important rule: The last index in an array is equal to one less than the number of ele- ments in the array. If you attempt to access an array element with an index that’s greater than the last index or less than zero, you’ll get a program crash. So if you specify phoneList[5] or phoneList[-1], you’ll get a program crash. As part of that crash, the Java Virtual Machine (JVM) prints an error message with the word “ArrayIndexOutOfBoundsException” in it. ArrayIndexOutOfBoundsException is an exception. You’ll learn about exceptions in Chapter 15, but for now, just think of an exception as a so- phisticated type of error that can be used by programmers to determine the source of a bug.
Now that you know how to access an array element, let’s put it to use. Here’s how you can change the first phone number to 2013434:
phoneList[0] = 2013434;
And here’s how you can print the second phone number:
System.out.println(phoneList[1]);