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<
No, there's no difference.
Both create an array with 0 elements.
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.
There is absolutely no difference.
int[] a = new int[0]
is to be preferred because it shows the intention of creating an empty array.
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.
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.