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?