I often see arrays being initialized like this:
String[] array = new String[] { \"foo\", \"bar\", \"baz\" };
But reading the Language Basic
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
.
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.
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.