Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array initialisation doubt.

 
Rajesh Shinde
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can anyone please explain how does the below code compiles?

int[] i=new int[][]{{1}}[0];
 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is like the following
 
Larry Chung
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajesh Shinde wrote:Hi,
Can anyone please explain how does the below code compiles?

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


Ah, yes. This is a good one.

To analyze:
1. on the left side of the equation you have a one-dimensional array.
2. on the right side of the equation you have an anonymous two-dimensional array
3. the equation can be broken down in these steps:
new int[][] // instantiates anonymous array
new int[][]{{1}} // initialize the anonymous array with one single element, "1", which automatically goes to position [0][0]
int[] i = new int[][]{{1}}[0] // obtains all the elements in row [0] of the anonymous array (which is just "1") and put into one-dimensional array i.

i array ends up getting "1" as the element at position 0.

It would be clearer (and much more fun) if you try this in the debugger mode on your IDE and watch the array variable, i.
 
Rajesh Shinde
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it..
Thanks Ankit,Larry.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic