BlazeRyder BlazeRyder - 10 months ago 54
Java Question

Multidimensional arrays code results in "ArrayIndexOutOfBoundsException" error

I am doing a project for school that deals with arrays and I have run into a problem. I was wondering if anybody could explain the error that I am getting. Here is my code:

public class ArrayPrinter
public static void main(String[] args)
int [] oneD = {5, 6, 7, 8 };

int[][] twoD = {{2, 4, 6, 8},
{8, 7, 9, 1},
{3, 5, 1, 2}};

int[][] twoD2 = {{1, 2},
{3, 4, 5},
{7, 8, 9}};



System.out.println(" ");


public static void printArray(int[] arr) {

int size = arr.length;
for(int i=0;i< size; i++){

public static void printArray(int[][] arr)

System.out.println("[ ");

for (int row = 0; row < arr.length; row++){


for (int i = 0; row < arr[row].length; i++)



I am getting an error when I run this in Eclipse. This is my output:






Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

at ArrayPrinter.printArray(

at ArrayPrinter.main(

How can I fix this error? And could you please explain why, rather that just do it for me?

Answer Source

Think about what you're doing in printArray(int[][] arr):

for (int row = 0; row < arr.length; row++){

This loops over the rows of the array. Remember, all those rows are arrays. At this point, arr[row] has type int[]. You have a printArray function that accepts an int[], so call that. The part where you loop over i is unnecessary.

Your IndexOutOfBoundsException occurs when you try to access an element of an array that is out of bounds. For example:

int[] arr = {42};
arr[3] // IndexOutOfBoundsException! arr has length 1, so arr[3] is out of bounds

You are getting the error because you are trying to loop over i, but the condition for termination is row < arr[row].length. That means that on the first iteration row will be 0. It will enter the i loop, and it will check if 0 < twoD2[0].length (it is) and then it will access twoD2[i]. Then it increments i and performs the check again, but row has not been updated! If a condition is true at the entry of a loop and you don't change the variables that are used in the condition, you will never exit the loop. Thus i never stops incrementing and eventually you try to access twoD2[4] and get the exception.