0

I'm working on a 2D array. The problem is really simple but I can't figure it out. When I try to access the value from index array[i-1][j] it is throwing a Null Pointer exception. While it seems completely legitimate to me to access a index like array[2-1][2] . Why it is not working? Is there any logic behind why I can't access array from one back index OR am I doing it wrong please explain.

Code to declare and initialize array:

this.Result = new Integer[len][6];

Code where Null pointer exception occurring:

for(int i=0;i<Result.length;i++) {
    if(i==0){
        Result[i][4]=0;
    }
    else if(Result[i][1]!=null) {
        Result[i][4]=(Result[i-1][2]+Result[i-1][3])+Result[i][2];
    }
}

Thanks in advance and please ignore grammar mistakes.

Sam
  • 492
  • 2
  • 13

3 Answers3

1

Well, it looks like the fields in your array have not been initialized properly. While something like int[] intArray = new int[length]; initializes all values in the array to zero, Integer[] integerArray = new Integer[length]; will just fill the array with null values.

Are you sure you initialized all fields in your array properly?

Tobias Brösamle
  • 598
  • 5
  • 18
1

You are creating an array of the wrapper Integer type. This means that the default value for all elements is null.

On this line:

Result[i][4]=(Result[i-1][2]+Result[i-1][3])+Result[i][2];

you are accessing elements that may be uninitialised, which causes the NullPointerException.

I suggest you use the primitive int type for the array elements to avoid performing operations on nulls. Another option will be initialise all elements with the value 0 prior to trying to access and perform calculations on them.

Danail Alexiev
  • 7,624
  • 3
  • 20
  • 28
0

Exception Raised due to Integer is a Wrapper Class in java. So, this 2-D array would be filled with null not 0.

if you replace your code

this.Result = new Integer[len][6]; with this.Result = new int[len][6];

error will resolved.

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52