Gpar
Gpar

Reputation: 181

Assignment of an array

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

Upvotes: 1

Views: 185

Answers (3)

MC Emperor
MC Emperor

Reputation: 22997

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?

Upvotes: 2

V-X
V-X

Reputation: 3029

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.

Upvotes: 0

codebox
codebox

Reputation: 20254

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

Upvotes: 0

Related Questions