Java Reference
In-Depth Information
Java also allows you to mix two syntaxes. In the same array declaration, you can place some brackets after the
data type and some after the variable name. For example, you can declare a two-dimensional array of int as follows:
int[] points2D[];
You can declare a two-dimensional and a three-dimensional array of int in one declaration statement as
int[] points2D[], points3D[][];
or
int[][] points2D, points3D[];
Runtime Array Bounds Checks
At runtime, Java checks array bounds for every access to an array element. If the array bounds are exceeded, an
java.lang.ArrayIndexOutOfBoundsException is thrown. The only requirement for array index values at compile
time is that they must be integers. The Java compiler does not check if the value of an array index is less than zero
or beyond its length. This check must be performed at runtime, before every access to an array element is allowed.
Runtime array bounds checks slow down the program execution for two reasons:
The first reason is the cost of bound checks itself. To check the array bounds, the length of
array must be loaded in memory and two comparisons (one for less than zero and one for
greater than or equal to its length) must be performed.
The second reason is that an exception must be thrown when the array bounds are exceeded.
Java must do some housekeeping and get ready to throw an exception if the array bounds are
exceeded.
Listing 15-13 illustrates the exception thrown if the array bounds are exceeded. The program creates an array of
int named test , which has a length of 3. The program cannot access the fourth element ( test[3] as it does not exist.
An ArrayIndexOutOfBoundsException is thrown when such an attempt is made.
Listing 15-13. Array Bounds Checks
// ArrayBounds.java
package com.jdojo.array;
public class ArrayBounds {
public static void main(String[] args) {
int[] test = new int[3];
System.out.println("Assigning 12 to the first element");
test[0] = 12; // index 0 is between 0 and 2. Ok
System.out.println("Assigning 79 to the fourth element");
// index 3 is not between 0 and 2. At runtime, an exception is thrown.
test[3] = 79;
System.out.println("We will not get here");
}
}
 
Search WWH ::




Custom Search