Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anonymous arrays

 
Phillipe Rodrigues
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between the below 2 declaration?

int[] intArray = {3, 5, 2, 8, 6}; // (1)
int[] intArray = new int[] {3, 5, 2, 8, 6}; // (2)

In what scenario is Anonymous arrays used?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no difference in the effect. The first version is a shortcut which can be used only in a variable initializer; i.e., you can't use it to pass arrays as method arguments, or for any other purpose.
 
Phillipe Rodrigues
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But the below is explained for (1)(2)

In (1), an array initializer block is used to create and initialize the elements. In (2), an anonymous array expression is used. It is tempting to use the array initialization block as an expression; for example, in an assignment statement as a short cut for assigning values to array elements in one go. However, this is illegal´┐Żinstead, an anonymous array expression should be used.

int[] daysInMonth;
daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Not ok.
daysInMonth = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // ok.

I am not getting the above explanation.

Please help in understanding.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The explanation says pretty much the same as what Ernest has written.

The first syntax, without "new int[]", is a shortcut syntax for variable initializers. You can't use that shortcut syntax in other places where you need an array literal, for example when calling a method.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And to reiterate with other words: both compile to the exactly same byte code. The only difference is that the shorter version takes less key strokes to type, but can be used in fewer places.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic