Getting the length of two-dimensional array

which 3?

You’ve created a multi-dimentional array. nir is an array of int arrays; you’ve got two arrays of length three.

System.out.println(nir[0].length); 

would give you the length of your first array.

Also worth noting is that you don’t have to initialize a multi-dimensional array as you did, which means all the arrays don’t have to be the same length (or exist at all).

int nir[][] = new int[5][];
nir[0] = new int[5];
nir[1] = new int[3];
System.out.println(nir[0].length); // 5
System.out.println(nir[1].length); // 3
System.out.println(nir[2].length); // Null pointer exception

Leave a Comment