• Post Reply Bookmark Topic Watch Topic
  • New Topic

Anonymous arrays  RSS feed

 
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?
 
author and iconoclast
Sheriff
Posts: 24218
38
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.
 
Java Cowboy
Sheriff
Posts: 16083
88
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.
 
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
Boost this thread!