Search code examples
javaarraysmultidimensional-arrayarrayofarrays

How multi dimensional array construct the index in java?


  1. int[][][] a = new int[3][3][5];
  2. int [][][] b = new int[2][][]; b[0] = new int[2]; // here why we get error. in the above code how java consist each braces.

in java how the above code will allocate memory in concept of array of array.


Solution

  • here why we get error. in the above code how java consist each braces.

    int [][][] b = new int[2][][];   //b is an array of (array of (array of int))
    b[0] = new int[2];               //b[0] is an (array of (array of int))
    

    You are assigning int[2] is only an (array of int) to b[0], hence giving you the error.

    b[0] = new int[2][];             //assign (array of (array of int)) to b[0] --> OK
    

    In short, b[0] is expecting a 2D array, and you are currently assigning it a 1D array and that is causing the error.