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.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.
In the square brackets, we have to specify the length of our array. In option(b), (c) and (d) square brackets are mission.So they are an incorrect way of initializing the array. Square brackets must be used to initialize an array as in option(a).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With