Q:

Error in simple java exercise

I am very new to java and I am having problem in solving a very easy exercise.
I have a good knowledge of different non OO programming languages so maybe the error is in the way I use object.
I want to compute the sum of all even elements in a matrix .
Here is my code :
public class start_problem4 {
        /**
     * @param args
     */
    public static void main(String[] args) {
        int[][] foo = new int[][] {
            new int[] { 1, 2, 3, 4},
            new int[] { 1, 2, 3, 4},
        };
    Matrix m=new Matrix(foo);
    System.out.println("the number is"+m.sumOfEvenNumbers());
    }
}

public class Matrix {

 private int[][] matrix;
 public Matrix(int[][] array)
 {
    matrix = array;
 }

 /**
  * Gets the sum of all the even numbers in the matrix
  * @return the sum of all the even numbers
  */
 public int sumOfEvenNumbers()
 {
         // TODO: Return the sum of all the numbers which are even
     int i,j,sum;
     sum=0;

     for(i=0;i<matrix[0].length;i++)
         for(j=0;j<matrix[1].length;j++)
             {
                System.out.println("i="+i+"  j="+j);
                if(matrix[i][j]%2==0)
                    sum=sum+matrix[i][j];
            }
     return sum;
 }

}

I received this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at Matrix.sumOfEvenNumbers(Matrix.java:24)
    at start_problem4.main(start_problem4.java:17)

A:

You want matrix.length to get the number of rows, instead of matrix[0].length and matrix[1].length which will give you the number of columns twice (the number of columns in the first and second row). Your matrix has the dimensions [2][4], but you're looping over it like it's [4][4].
Think of it as an array of arrays (because that's what it is). For example, the matrix
1 2
3 4

is actually
[[1,2],[3,4]]

The outer array has two elements (the number of "rows").

