Tracing output up to an off-by-one exception

The following Java statements run inside main with no exception handling. The program prints some numbers and then stops with a runtime exception.


Java
int[] data = {4, 7, 2, 9};
int total = 0;
for (int i = 0; i <= data.length; i++) {
    total += data[i];
    System.out.println(total);
}
System.out.println("Done");


What is the last number printed before the program stops? Give your answer as a whole number.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Exceptions and Error Types Questions: