Two dimensional array initializer followed by square brackets

By | August 10, 2019


I have a problem understanding this piece of code:

int[] it = new int[][]{{1}}[0];

Why is it compileable, and how can I understand such a declaration?


What you are doing here is:

  1. Declaring a new variable int[] it (which is a one-dimensional array)
  2. Assigning its value from the first element [0]
  3. of the two-dimensional array new int[][]
  4. which is initialized to be {{1}}

So you create a two-dimensional array which you initialize to contain an array which contains 1 and at the same time you take the first element of the outer array (which is a one-dimensional array containing 1) and assign it to your variable.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *