Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Declaration-Error in Java

Tags:

java

Why

int arr[][]=new int[5][];

declaration is perfectly fine but

int arr[][]=new int[][5]    

generates compile time error ?
Please do help me. I am not able to understand why is that so?

like image 550
cdev Avatar asked Dec 05 '25 18:12

cdev


1 Answers

int arr[][] (which is more typically written as int[][] arr) is an array, each element of which is in turn a reference to an array.

new int[][5] would mean "create an array of unknown length, each element of which is a reference to an array, each of length 5". Obviously, that doesn't make sense.

On the other hand, new int[5][] means "create a length-5 array, each element of which is a null reference to an array".

like image 64
Oliver Charlesworth Avatar answered Dec 08 '25 07:12

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!