15

How come the first call to someMethod doesn't compile without being explicit that it's String[]?

It's fine to use an array initializer to create a String[] array but you can't use it to pass an argument. Are the curly braces used in some other fashion for passing arguments that derails how I'd expect this to behave?

public void someMethod(String[] arr){
    //do some magic
}

public void makeSomeMagic(){

    String[] arr = {"cat", "fish", "cow"};

    //Does not compile!
    someMethod({"cat", "fish", "cow"});

    //This compiles!
    someMethod(new String[]{"cat", "fish", "cow"});

    //This compiles!
    someMethod(arr);
}

The compiler error is the following:

The method someMethod(String[]) in the type Moo is not applicable for the arguments (String, String, String)

1
  • 1
    Its only allowed at declaration time. It's a syntax thing Commented Dec 14, 2010 at 20:31

4 Answers 4

14

You can only use the { "hello", "world" } initialization notation when declaring an array variable or in an array creation expression such as new String[] { ... }.

See Section 10.6 Array Initializers in the Java Language Specification:

An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values

Sign up to request clarification or add additional context in comments.

Comments

5

If you don't want to use explicit String[], use:

public void someMethod(String... arr){
    //do some magic
}
…
someMethod("cm", "applicant", "lead");

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

Read more.

2 Comments

That will only work if he changes the signature to String... args.
Perfect, this gives me exactly what I was looking for. Thanks!
1

Or you can use varargs:

public void someMethod(String... arr){
    //do some magic
}

public void makeSomeMagic(){
    someMethod("cat", "fish", "cow");
}

It's basically a fancy syntax for an array parameter (vararg must be the last parameter in method signature).

Comments

0

You can use the curly braces to initialize an array. In every else case it is used to define blocks of statments.

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.