File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes difference: int[] a = {1,2,3}; int[] b = new int[3]{1,2,3}; Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "difference: int[] a = {1,2,3}; int[] b = new int[3]{1,2,3};" Watch "difference: int[] a = {1,2,3}; int[] b = new int[3]{1,2,3};" New topic

difference: int[] a = {1,2,3}; int[] b = new int[3]{1,2,3};

Sergii Trotsenko

Joined: Oct 23, 2012
Posts: 6
Hi guys!

On the interview I've been asked the following question and was confused to be honest. Can anybody please explain?

What is the difference between:

int[] a = {1,2,3};


int[] b = new int[]{1,2,3};

Ivan Jozsef Balazs

Joined: May 22, 2012
Posts: 867
My guess is that there is no difference beyond the syntax one: they get compiled the same way.

However if you manually declare the dimension, you do not make use of the compiler's ability to count the elements.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 38007
That is different from what the thread title shows. I suggest you try compiling the two lines and see what happens. Note the new Foo[] part is needed when you are reassigning the array, and redundant in the two lines you quoted.
I agree. Here's the link:
subject: difference: int[] a = {1,2,3}; int[] b = new int[3]{1,2,3};
Similar Threads
Array and Polymorphism questions.
Sierra & Bates SCJP 6 - C3 - Q3
Anonymous array
Array declaration and initialization
String array Vs String var args