int a[][]=new int[2][]; // It works without any error
Why is the second dimension missing in this snippet?
A 2D array is, technically, an array of arrays. The code that you have specified tells you how many arrays you want to have.
You can further initialize this as follows:
int a[][] = new int[2][];
a[0] = new int[3];
a[1] = new int[5];
Something like new int[2][2]
is nothing more than a condensed version of the code above.
It's not mandatory because the second dimension is not required to calculate how much memory is required to hold the array.
Compare the following:
int[] a = new int[2];
In this case the JVM needs to be instructed to allocate space for one array that holds two integers.
On the other hand:
int[][] = new int[2][];
In this case the JVM needs to be instructed to allocate space for two references to integer array objects. It doesn't matter what size these integer array objects end up being, as it doesn't change the size of the reference.
In fact, these two arrays can have different sizes or even not be created at all.
Second dimension in array is optional in Java. You can create a two dimensional array without specifying both dimension e.g. int[4][] is valid array declaration.
The reason behind that is Java doesn't support multi-dimensional array in true sense. In a true two dimensional array all the elements of array occupy a contiguous block of memory , but that's not true in Java.
Instead a multi-dimensional array is an array of array. For example two dimensional array in Java is simply an array of one dimensional array like String[][] is an array of array of String[] or "array of array of strings". This diagram shows how exactly two dimensional arrays are stored in Java :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With