Java Reference
In-Depth Information
A program with the preceding two lines of code produces a compilation error when rat-
ing[20] is used in a statement. The error occurs because the rating array does not have
a slot 20; it has 20 slots that begin at 0 and end at 19. The Java compiler would make
note of this by stopping with an ArrayIndexOutOfBoundsException error.
The Java interpreter also notes an error if the array subscript is calculated when the pro-
gram is running and the subscript is outside the array's boundaries. You learn more about
errors, which are called exceptions, on Day 7, “Exceptions, Assertions, and Threads.”
One way to avoid accidentally overrunning the end of an array in your programs is to use
the length instance variable. The following statement displays the number of elements in
the rating object:
System.out.println(“Elements: “ + rating.length);
Changing Array Elements
As you saw in the previous examples, you can assign a value to a specific slot in an array
by putting an assignment statement after the array name and subscript, as in the follow-
ing:
temperature[4] = 85;
day[0] = “Sunday”;
4
manager[2] = manager[0];
An important thing to note is that an array of objects in Java is an array of references to
those objects. When you assign a value to a slot in that kind of array, you are creating a
reference to that object. When you move values around inside arrays, you are reassigning
the reference rather than copying a value from one slot to another. Arrays of a primitive
data type, such as int or float , do copy the values from one slot to another, as do ele-
ments of a String array, even though they are objects.
Arrays are reasonably simple to create and modify, and they provide an enormous
amount of functionality for Java. Listing 4.1 shows a simple program that creates, initial-
izes, and displays elements of three arrays.
LISTING 4.1
The Full Text of HalfDollars.java
1: class HalfDollars {
2: public static void main(String[] arguments) {
3: int[] denver = { 2500000, 2900000, 3500000 };
4: int[] philadelphia = new int[denver.length];
5: int[] total = new int[denver.length];
6: int average;
7:
8: philadelphia[0] = 2500000;
9: philadelphia[1] = 2900000;
10: philadelphia[2] = 3800000;
Search WWH ::




Custom Search