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 Anonymous arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Anonymous arrays" Watch "Anonymous arrays" New topic

Anonymous arrays

Phillipe Rodrigues
Ranch Hand

Joined: Oct 30, 2007
Posts: 165
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

Joined: Jul 08, 2003
Posts: 24195

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.

[Jess in Action][AskingGoodQuestions]
Phillipe Rodrigues
Ranch Hand

Joined: Oct 30, 2007
Posts: 165
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

Joined: Aug 16, 2005
Posts: 15042

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
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.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
It is sorta covered in the JavaRanch Style Guide.
subject: Anonymous arrays
jQuery in Action, 3rd edition