Reputation: 2527
Syntax aside, is there any difference between the following two statements?
String[] str = { "test" };
and
String[] str = new String[] {"test"};
Upvotes: 1
Views: 92
Reputation: 500475
Let's see:
// String[] str1 = { "test" };
0: iconst_1
1: anewarray #16 // class java/lang/String
4: dup
5: iconst_0
6: ldc #18 // String test
8: aastore
9: astore_1
// String[] str2 = new String[] {"test"};
10: iconst_1
11: anewarray #16 // class java/lang/String
14: dup
15: iconst_0
16: ldc #18 // String test
18: aastore
19: astore_2
As you can see, they compile to identical bytecodes.
Note that outside intiailizations you generally have to use the second form.
Upvotes: 4
Reputation: 27516
No, there is no difference. Except if you want to pass it to the method
methodWhichAcceptsArray({"a", "b"}); //won't compile
methodWhichAcceptsArray(new String[] {"a", "b"}); //ok
Upvotes: 4
Reputation: 12196
No, there isn't.
String[] str = { "test" };
Will be interperated by the JVM as
String[] str = new String[] {"test"};
Upvotes: 2