Do you know Java: Varargs as Entry Point Parameter


Java 5 was one of those versions that brought much more features and syntactic sugars than any other of them. Varargs is one of those. This provides a very comfortable way to pass different number of arguments to a method. Can we use it anywhere?

Varargs is just a syntactic sugar, it can be used in a more flexible way than its predecessor, the typed array. It has the same characteristics which means it supports indexing, it has an attribute called length, it is iterable.

The Usual One

class Main {
    public static void main(String[] args) {
        System.out.println(args.length);
        for (String arg: args) {
            System.out.println(arg);
        }
    }
}

Varargs

class Main {
    public static void main(String... args) {
        System.out.println(args.length);
        for (String arg: args) {
            System.out.println(arg);
        }
    }
}

As mentioned that varargs is more flexible than its predecessor which means parameter passing is much easier. We do not have to deal with array creation and instantiation. On the other side, method with varargs parameter also accepts typed array.

class Main {
    public static void main(String... args) {
        basket("apple", "grape", "plum", "pear");
        String[] arr = {"apple", "orange", "lime", "lemon"};
        basket(arr);
    }

    public static void basket(String... args) {
       // ...
    }
}

Though varargs looks unusual, it is also available for parameter passing in main method since it works exactly at the same way how array works. Plus, it helps us passing different number of arguments without creating a new array.

Code can be found: https://github.com/torokmark/do-you-know-java