Reputation: 457
Which one is valid statement?
int[] x =new int[0]{};
new int[2];
int[] x=new int[][]{{1}}[0];
int[][] x = new int[]{0}[0][0];
int x= new int[2]{}[];
The correct answer is 3, and I can understand why it's not 1, 2 or 5, but I don't understand 3 or 4 mean.
Upvotes: 0
Views: 365
Reputation: 972
{}
you are not allowed to indicate the number of items in the array ergo int[0]
should be int[]
. So it should have been int[] x = new int[]{}
.int[] x = new int[2]
.new int[][]{{1}}[0]
is new int[]{1}
and thus int[] x = new int[]{1}
.new int[]{0}[0][0]
is trying to get a value of a two-dimensional array from a one-dimensional array and assign that to a the array x
. []
which not possible.Upvotes: 1
Reputation: 178253
1) int[] x =new int[0]{};
You cannot specify both a length 0
and an array initializer at the same time.
2) new int[2];
It's not a statement. It would become a statement if it were assigned to something else, among other possibilities.
3) int[] x=new int[][]{{1}}[0];
This declares and initializes a 1x1 2D array, with 1
being its only element. Then, array access is used to immediately access the "row" at position 0, the only such "row", which is itself a 1-length 1D array, and that is assigned to a 1D array.
4) int[][] x = new int[]{0}[0][0];
There is a lot wrong here. A 1-length, 1D array is created, but there are two array accesses on it. You can only supply one, because it's a 1D array.
5) int x= new int[2]{}[];
The extra []
doesn't do anything and is invalid syntax. Even if they're removed, you can't assign an int
array to a scalar int
. Also you can't specify a length and an array initializer {}
at the same time.
Upvotes: 2