passing a String array as argument

Viewed 56837

A String array can be declared and initialized in the following way:

String[] str = {"A", "B"};

but for a method which accepts a String array as argument, why can't the same be used there?

For example: if in the code below, i replace the call to show() from show(str); to show({"A" "B"});, it shows complier error. Why?

public class StringArray {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] str = {"A", "B"};
        show(str);
    }
    static void show(String[] s) {
        System.out.println(s[0] + s[1]);
    }
}

The compiler errors shown are:

StringArray.java:9: illegal start of expression
                show({"A", "B"});
                     ^
StringArray.java:9: ';' expected
                show({"A", "B"});
                      ^
StringArray.java:9: illegal start of expression
                show({"A", "B"});
                         ^
StringArray.java:9: ';' expected
                show({"A", "B"});
                          ^
StringArray.java:9: illegal start of type
                show({"A", "B"});
                               ^
StringArray.java:11: class, interface, or enum expected
        static void show(String[] s) {
               ^
StringArray.java:13: class, interface, or enum expected
        }
        ^
7 errors

Also using show(new String[] {"A", "B"}); is allowed. How is new String[]{"A", "B"} different from {"A", "B"} when passing them as method arguments? Thanx in advance!

8 Answers
Related