-1

I am simply trying to iterate through every variable in an array of arrays:

Here's the working code:

    int[][] mArray;
    mArray = new int[2][2];

    mArray[0][0] = 1;
    mArray[0][1] = 2;
    mArray[1][0] = 3;
    mArray[1][1] = 4;

    for (int i = 0; i < mArray.length; i++)
    {
         for (int x = 0; x < mArray[i].length; x++)
         {
            System.out.println(mArray[i][x]);
         }
    }    

This prints out:

1 2 3 4

So Everything's fine.

However if I replace

"for (int x = 0; x < mArray[i].length; x++)"

with

"for (int x = 0; x < mArray[x].length; x++)"

It get the following error: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2".

Can anyone explain why this error happens to occur? Both mArray[i].length and mArray[x].length result in a value of "2", so why does the second option not work?

Thanks in advance :)

Skilla123
  • 81
  • 1
  • 1
  • 7
  • 2
    because the condition is evaluated every iteration. And if you change `x` then it has to access a different element of the array and if `x == 2` it will try to access the array `mArray` out of bounds – UnholySheep May 01 '17 at 14:10
  • Because mArray has a total length of 4 rows. So i becomes 0, 1, 2, 3. But each row of your array provides only 2 columns. Therefore it is correct that you get ArrayIndexOutOfBoundsException when you index with i. x instead increases columnwise and will never overstep 1. –  May 01 '17 at 14:11
  • By the way it is often preferable to use "enhanced for loops" for iterating over arrays and collections - that way it's easier to avoid out of bounds exceptions – UnholySheep May 01 '17 at 14:14

1 Answers1

-1

Explanation is simple.

for (int x = 0; x < mArray[x].length; x++) {  
  // body  
}  

Before iterations: x=0
Statements execution order:
- 1st iteration: 0 < mArray[0].length == true; execute body; increment x (x==1)
- 2nd iteration: 1 < mArray[1].length == true; execute body; increment x (x==2)
- 3rd iteration: 2 < mArray[2].length cause ArrayIndexOutOfBoundsException, because x==2 and length of mArray is 2

UPD: totally, it's wrong logic to replace i with x in inner cycle, because i - it's row counter, and x - counter for columns.

Bor Laze
  • 2,458
  • 12
  • 20