0

Q. How to initialize arrays dynamically in Java?

I'm trying to store some metrics in arrays by using the following code.

 public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    int t = in.nextInt(); // outer metric size 
    int [] n = new int[t]; // inner square metric e.g. 3x3
    int [][][] a = new int[t][][]; // e.g. 2x3x3, 10x3x3

    //input block
    for (int h=0; h<t; h++){
        n[h] = in.nextInt(); //inner square metric dimensions
        for (int i=0;i<n[h];i++){
            for (int j=0;j<n[h];j++){
                a[h][i][j] = in.nextInt();    //metric values
            }
        }
    }

results in Null Pointer Exception which in turn is an array reference expected error. Changing the arrays to fixed size, doesn't cause this issue as expected.

  int [] n = new int[70];
  int [][][] a = new int[70][10][10];

Therefore, I would like to understand the right way to initialize dynamic arrays.

1
  • 2
    You never initialize the middle Array section. int [][][] a = new int[t][<here>][]; So you will have a container of null values Commented Apr 9, 2019 at 21:42

1 Answer 1

1

You have to allocate a new int[][] in the outer loop. Something like,

n[h] = in.nextInt(); //inner square metric dimensions
a[h] = new int[n[h]][n[h]]; //add this
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Elliott. I've two statements that allocates memory to the array 'a'. First being int [][][] a = new int[t][][]; and second being a[h] = new int[n[h]][n[h]]; From what I understand, Initially I had initialized a one dimensional array and the next statement is allocating a 2D array for the earlier initialization. I would like to ask, if this is a hack for my code or could it be a standard practice that I should be able to use going forward?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.