VWeber
VWeber

Reputation: 1261

Difference in Array initialization

While looking over a source file, i saw two ways of array initialization. I wonder is there a difference between

int[] value = new int[0];

and

int[] value_next = new int[]{};

?

Upvotes: 3

Views: 169

Answers (5)

Jean Logeart
Jean Logeart

Reputation: 53809

There is absolutely no difference.

int[] a = new int[0] is to be preferred because it shows the intention of creating an empty array.

Upvotes: 1

Maroun
Maroun

Reputation: 95948

Now the proof (and an exercise):

Create two classes, each containing one declaration. Compile them to get .class files.
On each of the two created files, do:

javap -c yourClass

To see the bytecode.

Now you can answer your own question.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234655

There is no difference, although in the second case you have redundant [].

Personally I prefer to use int[] value_next = {} to create an empty array.

In my opinion, int[] value = new int[0]; can, on rapid reading, look like you're creating an array with one element in it with initial value of 0. During a 3am debugging session I really appreciate clarity.

Upvotes: 1

peter.petrov
peter.petrov

Reputation: 39437

No, there's no difference.

Both create an array with 0 elements.

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

Actually there is no difference. It's Syntactic sugar in java array declaration.

The first type declaration is less confusing, at least for me :).

Note: I'm not sure why you given the length as zero while declaring.

If possible, go through https://stackoverflow.com/a/19558179/1927832 for some advantages over another.

Upvotes: 6

Related Questions