Two dimensional array error while printing array : array index out of bond

public class TwoDarray {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int a[][] = new int[2][2];
        a[0][0] = 0;    a[0][1] = 1;    a[0][2] = 2;
        a[1][0] = 3;    a[1][1] = 4;    a[1][2] = 5;
        a[2][0] = 6;    a[2][1] = 7;    a[2][2] = 8;
        for(int i=0;i<=2;i++)
        {
            for(int j=0;j<=2;j++)
            {
                System.out.print("t"+a[i][j]);
            }
            System.out.println();

        }

    }
}

I’m using eclipse and it gives error:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 2 at TwoDarray.main(TwoDarray.java:7)

I think my code is ok! but please suggest if I had done somthing wrong…

In one book they give structured form of array.twoDarray

and for that following code is also given: enter image description here

My structure of array is just similar to this only I have 2 rows and 2 columns.

Answer

Indexes are one-larger when initializing arrays:

int a[][] = new int[3][3];

Leave a Reply

Your email address will not be published. Required fields are marked *