Z i i t o x
Z i i t o x

Reputation: 25

NullPointerException in Java while trying to print an array

The thing is that I'm trying to print the matrix previously created in the constructor, but seems that it's empty.

Here's the code of the constructor:

public Matrix(int row_col){
    int [][] randomMatrix = new int[row_col][row_col];
    Random rand = new Random();
    if (row_col > 0 && row_col < ROW_LIMIT && row_col < COL_LIMIT)
    for (int i = 0; i < randomMatrix.length; i++) 
     for (int j = 0; j < randomMatrix[0].length; j++)
         randomMatrix[i][j] = rand.nextInt(51);
}

And the code of the method print:

public void print(){
    int row = randomMatrix.length;
    int col = randomMatrix[0].length;
    for(int i=0 ; i < row ; i++)
     for(int j=0 ; j < col ; j++)
        System.out.print(randomMatrix[i][j]);
}

Greetings!

Upvotes: 2

Views: 102

Answers (3)

Abubakkar
Abubakkar

Reputation: 15664

It is beacuse you have declared and initialized your array randomMatrix inside your constructor and as soon as the contructor's code is executed your randomMatrix array goes out of scope of print method.

And so when you try to access it in print method there is no such randomMatrix object, so you get NullPointerException

Upvotes: 0

Miquel
Miquel

Reputation: 15675

It looks like randomMatrix is defined directly in the scope of the constructor, and is not being stored in a field of the class.

If you already have a randomMatrix as a field, remove the int[][] in the first line of the constructor method, so you refer to the field instead of declaring a new variable.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691775

Replace

int [][] randomMatrix = new int[row_col][row_col];

by

this.randomMatrix = new int[row_col][row_col];

The constructor initializes and fills a local variable instead of initializing and filling the instance field used by the print() method.

Upvotes: 4

Related Questions