Alex Rivera | Logout

Java array initialization within argument list

Asked 2010-12-14T20:29:35.340
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)

Edit
Report

1 Answer

0

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

answered 2010-12-14T20:35:57.797

Your Answer