29

In Java, it is completely legal to initialize a String array in the following way:

String[] s = {"FOO", "BAR"};

However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed:

Test t = new Test({"test"});

But this works again:

Test t = new Test(new String[] {"test"});

Can someone explain why this is?

Hermann Hans
  • 1,798
  • 1
  • 13
  • 24

3 Answers3

45
String[] s = {"FOO", "BAR"};  

this is allowed at declaration time only

You can't

String[] s;
s={"FOO", "BAR"};  
jmj
  • 237,923
  • 42
  • 401
  • 438
5

Because Type[] x = { ... } is an initialization syntax for arrays. The { ... } is interpreted in a specific way only in that specific context.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
3

For you want a simple way to pass a String array, I suggest you use varargs

class Test {
   public Test(String...args);
}

// same as new Test(new String[] { "test", "one" })
Test t = new Test("test", "one"); 
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130