Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why second dimension is not mandatory in 2d array in java?

Tags:

java

int a[][]=new int[2][]; // It works without any error

Why is the second dimension missing in this snippet?

like image 202
Rohit Chugh Avatar asked Aug 09 '17 05:08

Rohit Chugh


3 Answers

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.

like image 183
Joe C Avatar answered Nov 02 '22 23:11

Joe C


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.

like image 33
Robby Cornelissen Avatar answered Nov 02 '22 23:11

Robby Cornelissen


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 :enter image description here

like image 39
daemonThread Avatar answered Nov 03 '22 00:11

daemonThread