Two Dimensional Array Declaration and Initialisation in Java

String[][] twoD3;
twoD3 = {{"1234", "5435", "2345"}, {"pebbles"}};

What is the problem with the above array initialization? Why am I getting compile error? The error is:

Syntax error on token ; ,, expected.

Jon Skeet
people
quotationmark

This has nothing to do with it being an array of arrays. You'll see the same error with this simpler code with a single array:

String[] array;
array = { "foo", "bar" };

You can't do that - an array initializer can only be used on its own within a declaration, e.g.

String[] array = { "foo", "bar" };

For a normal expression (on the right hand side of the assignment operator), you need an array creation expression, using the new keyword and specifying the array type:

String[] array;
array = new String[] { "foo", "bar" };

Or for your precise example:

String[][] twoD3;
twoD3 = new String[][] {{"1234", "5435", "2345"}, {"pebbles"}};

(Or just assign the value at the point of declaration, of course.)

people

See more on this question at Stackoverflow