Reputation: 153
I've a little confusion, when we declare & initialize a 2D array in java like given below
int arr[][]={{1,2,3,4},{4,3,2,1}};
This work correct, but when do do the above action like given below
int arr[2][4]={{1,2,3,4},{4,3,2,1}};
Then why it generates an error? Why can't we fix the size of rows and columns and then assign values in same statement? I know that we can do that separately using loops, something like arr[0][0]=345;
and so on, but why can't we do it like this?
int arr[4][2]={{1,2,3,4},{4,3,2,1}};
Upvotes: 0
Views: 2025
Reputation: 545
That’s because Java is not C language.
When you write int arr[][] = {{1, 2, 3, 4}, {4, 3, 2, 1}};
, you declare and initialize a multidimensional array of 2 by 4. It is equivalent to the C language initialization you proposed (int arr[2][4] = {{1, 2, 3, 4}, {4, 3, 2, 1}};
)
In Java, we preferably declare arrays in a Java-style manner:
int[][] arr = {{1, 2, 3, 4}, {4, 3, 2, 1}};
where int[][]
is just a type identifier, we cannot specify size.
Moreover, in Java, we can initialize a 2D array that is not rectangular:
int[][] arr = {{1, 2, 3, 4}, {4, 3}};
If you want to declare an array of specific size, but don’t want to specify all it’s values at once, the only solution is to use new
:
int[][] arr = new int[2][4];
arr[0][0] = 1;
Upvotes: 4