6

As far as I can tell, this code:

int[] numbers = new int[] { 1, 2 };

is the same as this code:

int[] numbers = { 1, 2 };

In fact, the compiled .class disassembles to the same code:

 1: newarray       int
 3: dup
 4: iconst_0
 5: iconst_1
 6: iastore
 7: dup
 8: iconst_1
 9: iconst_2
10: iastore
11: astore_1
12: iconst_2

However, similar code does not always perform the same way, or even compile. For example, consider:

for (int i : new int[] { 1, 2 }) {
    System.out.print(i + " ");
}

This code (in a main method) compiles and prints 1 2. However, removing the new int[] to make the following:

for (int i : { 1, 2 }) {
    System.out.print(i + " ");
}

generates multiple compile-time errors, beginning with

Test.java:3: error: illegal start of expression
for (int i : {1, 2} ) {
             ^

I would assume that the difference between these two examples is that in the first example (with int[] numbers), the type int is explicitly stated. However, if this is the case, why can't Java infer the type of the expression from the type of i?

More importantly, are there other cases where the two syntaxes differ, or where it is better to use one than the other?

wchargin
  • 15,589
  • 12
  • 71
  • 110
  • @LuiggiMendoza Thanks for the helpful link. However, I'm not sure that it completely answers the question: namely, are there other cases where the syntaxes differ? – wchargin May 28 '13 at 05:06
  • Check all the answers, not just the top one. – Luiggi Mendoza May 28 '13 at 05:07
  • 2
    I assume you're referring to [this one](http://stackoverflow.com/a/16697404/732016) by erickson. That answer does explain it for methods, but not for `for` loops, where the type is explicitly stated and there is no risk of circularity. – wchargin May 28 '13 at 05:09
  • 3
    As stated there, there's no way the compiler can infer the type of the array, so you will need an anonymous array i.e. use `new int[]{ }`. – Luiggi Mendoza May 28 '13 at 05:10
  • How is there no way the compiler can infer the type? What about the declared type of the variable `i`? It's `int` - therefore the following one must be either `int[]` or `Iterable`, and it clearly can't be the second one. I don't see the ambiguity. – wchargin May 28 '13 at 14:21
  • You can use `int` to traverse a `byte[]` or a `char[]` as well... – Luiggi Mendoza May 28 '13 at 14:22

1 Answers1

2

From JLS #10.6. Array Initializers

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.

Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72