user2985842
user2985842

Reputation: 457

Multidimensional array declaration

Which one is valid statement?

  1. int[] x =new int[0]{};
  2. new int[2];
  3. int[] x=new int[][]{{1}}[0];
  4. int[][] x = new int[]{0}[0][0];
  5. 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

Answers (2)

Omoro
Omoro

Reputation: 972

  1. When you declare and initialize an array using {} 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[]{}.
  2. This is an initialization without a declaration so it should have been something like int[] x = new int[2].
  3. This is correct because it assigns a declaration to an item of two-dimensional array which is an array itself. So the array returned from new int[][]{{1}}[0] is new int[]{1} and thus int[] x = new int[]{1}.
  4. This is totally wrong and messed up. 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.
  5. Here as discussed already in point 1, plus trying to access an array with an empty index [] which not possible.

Upvotes: 1

rgettman
rgettman

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

Related Questions