Reputation: 1338
int[] a = new int[] {1, 2, 3};
And
int[] a = {1, 2, 3};
Are there any practical differences between those?
Upvotes: 3
Views: 84
Reputation: 10147
look at the bytecode from compiled class files, There is no difference.
public class XFace {
public void test1(){
int[] a = new int[] {1, 2, 3};
}
public void test2(){
int[] a = {1, 2, 3};
}
}
Compiled from "XFace.java"
public class XFace extends java.lang.Objec
public XFace();
Code:
0: aload_0
1: invokespecial #8; //Method java/
4: return
public void test1();
Code:
0: iconst_3
1: newarray int
3: dup
4: iconst_0
5: iconst_1
6: iastore
7: dup
8: iconst_1
9: iconst_2
10: iastore
11: dup
12: iconst_2
13: iconst_3
14: iastore
15: astore_1
16: return
public void test2();
Code:
0: iconst_3
1: newarray int
3: dup
4: iconst_0
5: iconst_1
6: iastore
7: dup
8: iconst_1
9: iconst_2
10: iastore
11: dup
12: iconst_2
13: iconst_3
14: iastore
15: astore_1
16: return
}
Upvotes: 0
Reputation: 200296
Your second form is just syntactic shorthand for the first form. They compile into exactly the same bytecode.
Upvotes: 0
Reputation: 96016
They are equivalent, no difference between the two.
new
keyword creates an object.. and you're creating.. an array, which is an object.
See Chapter 10. Arrays:
In the Java programming language, arrays are objects (§4.3.1)...
Upvotes: 2