Sonny Ghosh Sonny Ghosh - 1 year ago 74
Java Question

why does this toString() cause a NullPointerException and how do I fix it? (Java)

I've rewritten this code with both for and for each loops and keep on getting the NullPointerException. Why does occur when the for loops start?

package ghosh4ab;

public class APMatrix {
private int[][] neo;

public APMatrix(int r, int c, boolean enter) {
KeyboardReader reader = new KeyboardReader();
int[][] neo = new int[r][c];
if (enter == true) {
for (int i = 0; i < neo.length; i++) {
for (int j = 0; j < neo[i].length; j++) {
reader.readInt("Enter int: ");


public String toString(){
String s1 = "\n";
for (int[] rows: neo){
for (int val: rows)
s1+= val + "\t";
s1+= "\n";

return s1;

and here is how I ran it:

public static void main(String[] args) {
APMatrix m1 = new APMatrix(2,2, true);

Answer Source

You redeclared neo in the constructor instead of assigning it a value. You created a neo local variable in the constructor

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download