Java Reference
In-Depth Information
Assigning 12 to the first element
Assigning 79 to the fourth element
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at com.jdojo.array.ArrayBounds.main(ArrayBounds.java:14)
It is good practice to check for array length before accessing its elements. The fact that array bounds violation
throws an exception may be misused as shown in the following snippet of code, which prints values stored in an array:
/* Do not use this code, even if it works.*/
// Create an array
int[] arr = new int[10];
// Populate the array here...
// Print the array. Wrong way
try {
// Start an infinite loop. When we are done with all elements an
// exception is thrown and we will be in catch block and hence out of the loop.
int counter = 0;
while (true) {
System.out.println(arr[counter++]);
}
}
catch (ArrayIndexOutOfBoundsException e) {
// We are done with printing array elements
}
// Do some processing here...
The above snippet of code uses an infinite while loop to print values of the elements of an array and relies on the
exception throwing mechanism to check for array bounds. The right way is to use a for loop and check for array index
value using the length property of the array.
What Is the Class of an Array Object
Arrays are objects. Because every object has a class, you must have a class for every array. All methods of the Object
class can be used on arrays. Because the getClass() method of the Object class gives the reference of the class for
any object in Java, you will use this method to get the class name for all arrays. Listing 15-14 illustrates how to get the
class name of an array.
Listing 15-14. Knowing the Class of an Array
// ArrayClass.java
package com.jdojo.array;
public class ArrayClass {
public static void main (String[] args){
int[] iArr = new int[2];
int[][] iiArr = new int[2][2];
int[][][] iiiArr = new int[2][2][2];
 
Search WWH ::




Custom Search