Java Reference
In-Depth Information
The index of the last element in sums is 19. Using the index 20 is not valid,
although the compiler will let you. Be careful because the following statement
compiles:
sums[20] = 211;
However, at run time this statement causes an ArrayIndexOutOfBoundsEx-
ception to occur. Java arrays are different from arrays in other languages in
that Java arrays are objects. One benefit of this is that every array in Java has a
length attribute that contains the size of the array.
By using the length attribute, you can greatly reduce the likelihood of inad-
vertently accessing elements beyond the end of an array. The following for
loop prints out the elements in the sums array, using the length attribute as the
upper limit of the loop control variable:
for(int i = 0; i < sums.length; i++)
{
System.out.println(“sums[“ + i + “] = “ + sums[i]);
}
Notice that the Boolean expression in the for loop uses “less than”
sums.length, as opposed to “less than or equal to” sums.length. Because
sums is of size 20, the value of sums.length is 20. If we use less than or
equal to, we would access sums[20] in the loop and cause an exception to
occur. This is a common programming error.
Arrays of References
There are nine types of arrays in Java: There is an array type for each of the
eight primitive data types, and there is an array type for arrays of references.
The sums and temps array are examples of arrays of primitive data types. The
other type of array is an array of references. You can declare an array of any
reference type.
For example, the following statement declares a reference to an array of
Employee references:
Employee [] myCompany;
The variable myCompany can refer to any array of Employee references.
The following statement assigns myCompany to a new array of 500 Employee
references:
myCompany = new Employee[500];
Search WWH ::




Custom Search