0

I keep getting this error: Exception in thread "main" java.lang.NullPointerException. I'm not sure what's wrong here..

String[][][][] fourDArray = new String[numOfModules+1][3][][];
    String[] x = new String[1];
    x[0] = splitArray[0];   
    fourDArray[0][0][0] = x;
  • 1
    it is obvious, you don't have defined the third and fourth dimension size – Mohsen_Fatemi Sep 23 '17 at 20:18
  • When the sizes of array (or it's dimensions) are not declared, it cannot be used. It yet doesn't have the 0th element. If you want it to be dynamic, you have to use `ArrayList` – Mike B Sep 23 '17 at 20:20

3 Answers3

0

When you define an multi-dimension array, you have to define at least first dimension size. This is initial array. All other dimensions are just sub-arrays. The could be not defined, i.e. you get NPE when you read it.

With step to step:

  1. Define an 4-dimension array. First dimension with size 2. It means that we define one-dimension array with 2 element, where each element is trhee-dimension array which is Object, then default value is null.

    int[][][][] arr = new int[2][][][];

  2. Then we are able to work with next dimension with same way.

    arr[0] = new int[2][][]; arr[1] = new int[2][][];

  3. Thats why you get NPE. You have to manually define all dimension with new statement (JVM does not do it automatically).

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

Size of the 3rd and 4th dimension in the array is not known which is resulting in the error.

Please specify the size if you need to use it.

Something like this.

 String[][][][] fourDArray = new String[10][3][6][7];
Isha Agarwal
  • 420
  • 4
  • 12
0

It is OK not to allocate (define size) a dimension on initialization, but it wont work if you try to access it before allocation. That is what happens in your code with the 3rd dimension.

    //Since you are going to access 3rd dimension later, you will have to allocate it
    String[][][][] fourDArray = new String[numOfModules + 1][3][3][];
    String[] x = new String[1];
    x[0] = "some_string";
    //So, it is OK to access (index by) 3rd dimension
    fourDArray[0][0][0] = x;
y.luis.rojo
  • 1,794
  • 4
  • 22
  • 41