Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing array with values - should I explicitly instance the class or not?

Tags:

java

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.

like image 854
Fabrício Matté Avatar asked Mar 02 '13 17:03

Fabrício Matté


People also ask

What is the proper way of initializing array?

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.

How do you initialize an array with values?

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.

Which is the incorrect way of initializing an array?

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).


2 Answers

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.

like image 178
NPE Avatar answered Oct 13 '22 12:10

NPE


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.

like image 44
Matt Ball Avatar answered Oct 13 '22 13:10

Matt Ball