difference fn(String... args) vs fn(String[] args)

Nrj picture Nrj · Nov 19, 2008 · Viewed 65.2k times · Source

Whats this syntax useful for :

    function(String... args)

Is this same as writing

    function(String[] args) 

with difference only while invoking this method or is there any other feature involved with it ?

Answer

bruno conde picture bruno conde · Nov 19, 2008

The only difference between the two is the way you call the function. With String var args you can omit the array creation.

public static void main(String[] args) {
    callMe1(new String[] {"a", "b", "c"});
    callMe2("a", "b", "c");
    // You can also do this
    // callMe2(new String[] {"a", "b", "c"});
}
public static void callMe1(String[] args) {
    System.out.println(args.getClass() == String[].class);
    for (String s : args) {
        System.out.println(s);
    }
}
public static void callMe2(String... args) {
    System.out.println(args.getClass() == String[].class);
    for (String s : args) {
        System.out.println(s);
    }
}