Naman
Naman

Reputation: 2373

Array as method argument

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
        }
    }

Upvotes: 0

Views: 164

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1503759

That's just the way the language is specified. From section 10.6 of the JLS:

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.

So you've seen it working in a declaration, and an array creation expression is the form which includes new ArrayElementType at the start:

myMethod(new String[] {"A"});

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:

// C# 3
MyMethod(new[] {"A"});

You still need the new[] part though.

Upvotes: 4

blackcompe
blackcompe

Reputation: 3190

You can, although your syntax is a bit off.

mymethod(new String[]{"A"});

Upvotes: 5

Makoto
Makoto

Reputation: 106508

You can't pass an array like that. Declare it as a variable, then pass the variable to the method instead.

Upvotes: 1

Related Questions