3

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

?

3
  • 2
    No difference, I prefer the first. Commented Feb 10, 2014 at 9:41
  • 4
    Your second line should say int[] value_next = {} to at least show some advantage of it. Commented Feb 10, 2014 at 9:43
  • @MarkoTopolnik That's nice ! Commented Feb 10, 2014 at 9:44

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It was just a example. I saw it in "toArray(T[] a)" of a ArrayList where the zero length is fine.
2

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.

1 Comment

+1 for teaching how to fish. Now save the text of this answer and apply it to every 10th question on SO :)
1

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.

Comments

1

There is absolutely no difference.

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

Comments

0

No, there's no difference.

Both create an array with 0 elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.