• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

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

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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};

and

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

Thanks!
 
Rancher
Posts: 1017
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Marshal
Posts: 59769
188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!