1

I have a code

 String ejgStr[] = new String[][]{{null},new String[]{"a","b","c"},{new String()}}[0] ;
 System.out.println(ejgStr[0]);

which compiles without error. From what I understand you can't create an array with non-matching square brackets.

On the left, we have String ejgStr[], which is 1-d array and

On the right, we have String[][]{some array}[0], which is 2-d array

These seem to have different dimensions but why do they successfully compile?

1
  • Better use String[] ejgStr =. The other allowed notation was added for compatibility with C/C++, and is a dead giveaway of a novice or C/C++ programmer. ;) Commented Jul 15, 2016 at 8:12

4 Answers 4

2

You are assigning a one-dimensional String[] array to the first dimension of an inline two-dimensional String[][] array. Have a look the comments:

String ejgStr[] =
    new String[][] {
                     { null },                   // a null 1D String array
                     new String[] {"a","b","c"}, // a 1D String array containing a,b,c
                     { new String() }            // a String array containing empty String
                   }[0];                         // access the { null } 1D array

I expect your assignment to be equivalent to doing this:

String ejgStr[] = { null };
Sign up to request clarification or add additional context in comments.

Comments

1

You assign a 1D array to the ejgStr refference. If you look at the end of the first statemend, you will see that you have a [0] index specified which means you will assign the first array (position 0) to your referrence. If you remove the [0] you will receive a compilation error.

Comments

1

new String[][]{...} is a 2D array.
new String[][]{...}[0] is the first element of a 2D array, which is a 1D array.
That's what you're assigning to String ejgStr[].

Comments

-1

String ejgStr[] is just a reference to a variable in heap space. you're pointing to first dimensional of 2D-dimensional array using [0] and make a reference of it in ejgStr[]. this is not common to get 1D from 2D array, but you can do it if you need and of course it wont make compile error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.