-2

I have the following program that scans a 2-dimensional matrix and checks for the position of 0s in rows and columns and make the entire row and column(rows and columns where 0 exists) , 0s in the matrix.

public static int[][] makeMatZero(int[][] matrix){
    Boolean[] row = new Boolean[matrix.length];
    Boolean[] col = new Boolean[matrix[0].length];

    for(int i = 0;i< matrix.length;i++){
        for(int j = 0;j< matrix[0].length;j++){
            if(mat[i][j]==0){
                row[i]=true;
                col[j]=true;
            }
        }

    }

    for(int i = 0;i<row.length;i++){
        if(row[i]){
            removeRow(i,mat);
        }
    }

    for(int i = 0;i<col.length;i++){
        if(col[i]){
            removeCol(i,mat);
        }
    }
    return matrix;


}


public static void removeRow(int row, int[][] mat){
    for(int j  = 0;j<mat[0].length;j++){
        mat[row][j]=0;  

    }
}
public static void removeCol(int col, int[][] mat){
    for(int j  = 0;j<mat.length;j++){
        mat[j][col]=0;  

    }
}

I get a nullPointerException in the line if(row[i]) and if i comment it out, i get an exception in if(col[i]). I tried debugging and printed out the values of i and row.length/col.length. The value of i never crosses row.length/col.length, but i still get a nullPointerException. Any help in letting me know what the mistake is much appreciated.

P.S : I am trying to solve few questions in the book "Cracking the coding Interview" by Gayle Laakmann McDowell and the above mentioned is one of the questions in the Chapter Arrays and Strings. The above solution too is given in the book

N_B
  • 301
  • 2
  • 15

1 Answers1

6

Use a "small" boolean, not the Boolean class as type of your arrays, so all fields will be initialized with false instead of null (the latter leading to your NullPointerException).

Additional explanation: Boolean is a class, so the compiler performs so-called autoboxing for a line like this:

Boolean b = null;
if (b) 

becomes

Boolean b = null;
if (b.booleanValue())

Here it is obvious that calling .booleanValue() on null is not a good idea.

Florian Albrecht
  • 2,266
  • 1
  • 20
  • 25