Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
SCJP Online Training » Discussions

Q#57 of Diagnostic Test about array initialization

Hi Mr. Tyler,


In this question we are trying to have a single dimension array reference variable while the object is a multidimensional array.... Please help clarify.


Thanks,

Shachi

Hi Sanchi,


I think you are talking about the option C, which is the given correct answer. Well, let's see if are really trying to assign incompatible types.


So as the option C, we have this statement:


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


We know that the reference type (int[] it2) is in a one-dimension int array, so what we assign to this variable must be a one-dimension int array as well.


The tricky part goes with the object we assign (the right side part):


new int[][]{{1}}[0]


Remember, what we need to know is the type of the value that this expression returns. We have to go through this whole expression to realize what it returns.


Let's go from left-to-right...


new int[][]

- This one creates a two-dimension int array.


new int[][]{{1}}

- We assign '1' to the first element of the 2D array we just created, where the outer { } brackets represent the first dimension, and inner { } represents the second dimension. In other words, the outer { } bracket represents an array-of-array (which is the sense of 2D arrays). So each element in the outer bracket has to be another array, and that's why we have an inner { } block. In the inner { } block, it represents the elements of the second array, where elements are now just int values, so we can have some int values in here.


new int[][]{{1}}[0]

- we fetch the first element ('first' because the index is 0) of this 2D array. Since a 2D array is an array-of-arrays, the first element of this array is its inner one-dimension array. So the what this fetches is that inner 1D int array.


Since this 1D int array it returned is assignable to our reference, which is int[], this line compiles.


Does that make it a little bit clear?

Thanks a lot Mr. Tyler !! This really clarifies. I had not considered that last [0] represents the element inside the 2D array.

ExamLab © 2008 - 2024