Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in Array initialization

Tags:

java

arrays

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[]{};

?

like image 572
VWeber Avatar asked Feb 19 '26 10:02

VWeber


2 Answers

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.

like image 159
Suresh Atta Avatar answered Feb 20 '26 23:02

Suresh Atta


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.

like image 33
Maroun Avatar answered Feb 21 '26 00:02

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!