20

I often see arrays being initialized like this:

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

But reading the Language Basics - Arrays shows that the short syntax doesn't require explicitly instancing the constructor:

Alternatively, you can use the shortcut syntax to create and initialize an array:

 int[] anArray = { 
     100, 200, 300,
     400, 500, 600, 
     700, 800, 900, 1000
 };

So, assuming these two methods of initialization:

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

Is there any difference between these? Both seems to work the same, in that case should I assume that the second one implicitly calls the new String[] and the first one is just a more verbose way, or is there more to it behind the scenes?

Starting with Java so sorry if this is way too stupid of a question, but I couldn't find anything about this in the web.

3 Answers 3

21

The two methods are equivalent. Note, however, that the concise syntax can only be used in variable declarations. Outside variable declarations you have to use the verbose syntax:

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

    String[] array2;
    array2 = { "foo", "bar", "baz" };             // ERROR

For further discussion, see this answer.

Sign up to request clarification or add additional context in comments.

Comments

7

Is there any difference between these?

There is no difference in the end result. However, as per the JLS § 10.6, you cannot use the array initializer synax in every context.

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.

1 Comment

I do love spec links, thanks very much. But I believe NPE's answer is more clear/simpler for future Java starters that may come to read the question. +1 for both in any case. =]
0

Since arrays are intended to be mutable, it makes sense that each one is a new instance

String[] array1 = { "foo", "bar", "baz" };
String[] array2 = { "foo", "bar", "baz" };

i.e. modifying array1 won't affect array2.

1 Comment

I have a decent OO base and understand that each array is a new instance, the question was specifically whether new String[] made any difference in the initialization of the array.

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.