Java Reference
In-Depth Information
This simple program iterates through an array and adds the total number of hours from each
element together. Then, the total is output to the console. If you try to run it, though, you will
encounter an exception, as shown in Figure 6-9.
figure 6-9  
As before, you can track down the exception by the information shown in the error message. First,
you can see that it is an ArrayIndexOutOfBoundsException . The index that's out of bounds is 5,
and it occurred in line 10 of the program. If you look at line 10, it is the last line of the for loop, so
you know to check the iterator of the for loop. In the code, it was set to start from 0, the lower limit
of the array's index, and stop at hoursWorked.length , but the length is 5 and the index only goes
to 4. Simply changing the termination condition to i < hoursWorked.length will stop the loop at
4 (since 4 is less than 5) and avoid an out of bounds exception.
public class IndexExceptionExample {
public static void main(String[] args) {
int[] hoursWorked = {7,8,7,9,5};
int totalHours = 0;
for (int i = 0; i < hoursWorked.length; i++){
totalHours += hoursWorked[i];
}
System.out.println("Total Hours = " + totalHours);
}
}
Two other common exceptions you might encounter are StackOverFlowError and
OutOfMemoryError . These occur when the program you are running demands more memory than
your machine allows for Java or your IDE. The stack is the part of your memory allocated for
parameters and local variables. This can overflow when you are calling a method recursively or
when two methods call each other. The heap is where objects are allocated in memory. Creating too
many objects, often within an infinite loop, can quickly consume all the available memory. To see
these kinds of errors for yourself, try running the following small applications.
import java.util.ArrayList;
public class EndlessLoop {
static ArrayList<String> myStrings = new ArrayList<String>();
Search WWH ::




Custom Search