A Little Java 5 Idiom

In Java 5, an application's main function can be declared with varargs parameters instead of an array of Strings. For example:

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

Not a particularly astounding revelation: under the hood, varargs parameters are passed to the function as an array so the JVM sees no difference between a varargs main function and one declared to take a String array. However, it's easier to call a varargs main function from other Java code - in end-to-end tests for instance - and the resulting code is easier to read. For example:

private void runProgram() {
    Main.main("hello", "world");
}

instead of

private void runProgram() {
    Main.main(new String[]{"hello", "world"});
}

Because of this I've started declaring all my main functions with varargs parameters.

Copyright © 2007 Nat Pryce. Posted 2007-08-03. Share it.