1

Syntax aside, is there any difference between the following two statements?

String[] str = { "test" };

and

String[] str = new String[] {"test"};
2
  • You can't break the first into multiple statements. That's all. Commented Jan 16, 2014 at 19:38
  • No, this is just a shortcut syntax. And you can check by seeing the bytecode produced by this two snippet of code. Commented Jan 16, 2014 at 19:41

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

No, there isn't.

String[] str = { "test" };

Will be interperated by the JVM as

String[] str = new String[] {"test"};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.