Passing arrays as method parameters in Java

The following code uses simple String arrays in Java.

package javaarray;

final public class Main
{
    public void someMethod(String[] str)
    {
        System.out.println(str[0]+"\t"+str[1]);
    }
    public static void main(String[] args)
    {
        String[] str1 = new String[] {"day", "night"};
        String[] str2 = {"black", "white"};

        //Both of the above statements are valid.

        Main main=new Main();
        main.someMethod(str1);
        main.someMethod(str2);

        //We can invoke the method someMethod by supplying both of the above arrays alternatively.

        main.someMethod(new String[] { "day", "night" }); //This is also valid as obvious.
        main.someMethod({ "black", "white" }); //This is however wrong. The compiler complains "Illegal start of expression not a statement" Why?
    }
}

In the code snippet above, we can initialize arrays like this.

String[] str1 = new String[] {"day", "night"};
String[] str2 = {"black", "white"};

and we can directly pass it to a method without an assignment like this.

main.someMethod(new String[] { "day", "night" });

If this is so, then the following statement should also be true.

main.someMethod({ "black", "white" });

but the compiler complains: "Illegal start of expression is not an assertion" Why?

+5
source share
1 answer

According to the specification of the Java language ( 10.6. Array initializers )

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

, ({"foo", "bar"}):

  • : String[] foo = {"foo", "bar"};
  • : new String[] {"foo", "bar"};

.

15.10.

ArrayCreationExpression:
    new PrimitiveType DimExprs Dimsopt
    new ClassOrInterfaceType DimExprs Dimsopt
    new PrimitiveType Dims ArrayInitializer 
    new ClassOrInterfaceType Dims ArrayInitializer
+8

All Articles