We declare String array like-
String[] a={"A"};
But when a method has String array as argument, why can’t we call the method like-
mymethod({"A"});
Code-
class A{
static void m1(String[] a) { }
public static void main(String args[]){
m1(new String []{});//OK
m1({}); //Error
}
}
That’s just the way the language is specified. From section 10.6 of the JLS:
So you’ve seen it working in a declaration, and an array creation expression is the form which includes
new ArrayElementTypeat the start:Bear in mind that when it’s part of a declaration, there’s only one possible element type involved. For method invocations, it’s trickier – there could be multiple overloaded methods, etc. Basically, you’d need to make the expression
{"A"}evaluate as a string array on its own, before participating in overload resolution.For a bit of comparison, the same is true in C#, although C# 3 introduced implicitly typed arrays where the element type is inferred from the values, so you’d be able to write:
You still need the
new[]part though.