1

I saw this snippet when I was preparing for one of the certification exam on java. Can anybody please explain me how does this work?

public static void main(String args[]) {
    String str[] = new String[][] {
        { null },
        new String[] { "a", "b", "c" },
        { new String() }
    }[0];

    System.out.println(str[0]);
}

The o/p is null as expected but I am confused with the assignment of String array 's'.

  1. Is it a single dimension array or two-dimensional?
  2. What does [0] on the righthand side of the assignment mean?
  3. How does new String[] { "a", "b", "c" } work?

Thanks in advance GPAR

MC Emperor
  • 17,266
  • 13
  • 70
  • 106
Gpar
  • 181
  • 1
  • 1
  • 7

3 Answers3

2

I've split the statement into multiple lines, improving the readability

// First, the array is created, then it is stored into a variable.

// At last, store the result of code below into a String[].
String str[] =

// Create a two-dimensional array
new String[][] {
    // Add the first element to the two-dimensional array,
    // which is in fact a String[] with one null element in it.
    /* element #0 */ new String[] { null },

    // Add the second element to the two-dimensional array:
    // it's a String[] containing three strings
    /* element #1 */ new String[] { "a", "b", "c" },

    // Then add the third element to the two-dimensional array,
    // which is an empty string.
    /* element #2 */ new String[] { new String() }
}

// Then get the first element of our two-dimensional array,
// which returns a String[] with one null element in it.
[0];

So in fact, variable str now contains a String[] with index 0 being null.

At last, str[0] is printed on the screen, which was null.

To answer your questions:

  1. Variable str is a one-dimensional array. The notation String str[] is very ugly and confusing; it should be String[] str. And then you can see more easily that our variable is one-dimensional.
  2. [0] means get the first element of the array (arrays always start with index 0). A certain element of a two-dimensional array is always a one-dimensional array; with other words, a two-dimensional array is an array containing arrays.
    So that's why String[] str = new String[][] { ... }[0] is perfectly valid.
  3. new String[] { "a", "b", "c" } creates a string array containing three strings: "a", "b" and "c".
    So new String[] { "a", "b", "c" }[2] would return "c".

EDIT

Let me explain it step by step.

Step 1 — This is how we declare a String[] (a String array):

String[] myArray = new String[numberOfElements];

Step 2 — We can also immediately initialize the array with values:

String[] myArray = new String[] {
    "some value",
    "another value",
    "et cetera"
};

Step 2b — We do not need to mention the number of elements, because the compiler already sees that we initialize the array with three elements

String[] myArray = new String[3] {
                          //  ^
    "some value",         //  That number
    "another value",      //  is unnecessary.
    "et cetera"
};

Step 3 — Because we declare the array and immediately initialize it, we can omit the new statement:

String[] myArray = {
    "some value",
    "another value",
    "et cetera"
};

Step 4 — Next, we have a two-dimensional array, which is nothing more than an array of arrays.
We can first initialize the one-dimensional arrays and then dump them together in a two-dimensional array, like this:

String[] firstThree = { "a", "b", "c" };
String[] lastThree = { "x", "y", "z" };

String[][] myArray = new String[] {
    firstThree,
    lastThree
};

Step 5 — But we can also do that at once:

String[][] myArray = new String[] {
    new String[] { "a", "b", "c" },
    new String[] { "x", "y", "z" }
};

Step 6 — Now we said that we can omit the new statements (see step 3), because the array is initialized immediately after initialization:

String[][] myArray = {
    { "a", "b", "c" },
    { "x", "y", "z" }
};

Step 7 — Right?

Step 8 — Now we have your code:

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

And let us rewrite your code; effectively it's the same as your piece of code.

// Let us define a new two-dimensional string array, with space for three elements:
String[][] our2dArray = new String[3][];

// Then, let us fill the array with values.
// We will add a String array with exactly one element (that element is `null` by chance)
our2dArray[0] = new String[] { null };

// We define the contents for index 1 of our2dArray
our2dArray[1] = new String[] { "a", "b", "c" };

// At last, the last element:
our2dArray[2] = new String[] { new String() };
// Which is effectively the same as
// new String[] { "" };

We have initialized the array so far.

Step 9 — But then, do you see this snippet?:

}[0];

Step 10 — That means we just grab the first element of our newly created array and store that element to our famous variable named str!

String[] str = our2dArray[0]; // Variable str now contains a
// String array (String[]) with exactly one null-element in it.
// With other words:
// str = String[] {
//     0 => null
// }

Step 11 — Then if we print index 0 of our str array, we get null.

System.out.println(str[0]); // Prints null

Step 12 — You see?

MC Emperor
  • 17,266
  • 13
  • 70
  • 106
  • I think that example assignment is way too confusing. But to answer your first question, not all parts of the 2d array are used. First it is initialized, but then only the first element (index 0) is used. Your second question, however, I do not understand. – MC Emperor Oct 30 '14 at 13:02
  • I mean it looks like str[]=null; rather than str[0]=null; – Gpar Oct 30 '14 at 13:36
  • You say "it" looks like `str[] = null`. But to what refers "it"? With other words: *what* looks like `str[] = null`? – MC Emperor Oct 30 '14 at 13:56
  • Let me explain you my doubt in this way, String s[]=null; System.out.println(s);//prints null System.out.println(s[0]);//null pointer exception. My 2nd question was the code in my above snippet seems to assign null value to array itself not to the first element of the array i.e one in like the above code. In which way in my previous code str[0] gets the value null? @MC Emperpr – Gpar Oct 30 '14 at 16:36
  • That's why I would slap the one who created this example. Arrays are being explained, and then `null` values are involved. But I think I need more space than this comment to explain it to you. – MC Emperor Oct 30 '14 at 16:42
  • @Gpar If this post helped you, you can [mark the answer as accepted](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – MC Emperor Oct 31 '14 at 09:15
0

1> str is a one-dimensional array

2> the [0] returns the first element of the array (which in this case is another array)

3> new String[]{"a","b","c"} creates and initialises the string array, so that it contains the 3 specified strings - answers to this question might help you with the various syntax rules for this

Community
  • 1
  • 1
codebox
  • 18,210
  • 7
  • 54
  • 77
0

This is very ugly code.

this String str[]=new String[][]{{null},new String[]{"a","b","c"},{new String()}}[0]; create and initialize a jagged 2d array of String with some initialization and [0] is there to select the 0th String[] to be assigned to the new str variable (the value will be {null}).

the second line prints some value s[0] which is declared somewhere else.

V-X
  • 2,710
  • 15
  • 28