In Java code you have to use arrays a lot if you want to pass a variable number of arguments to a method. The main method is an excellent and prominent example.
public static void man(String[] args) {
…
}
Java 5.o introduces a new notation ( type … name ) which in my opinion is very elegant and readable. See the following program for example.
public class VarArgs {
public static void main(String ... args) { :-)
printUs("ONE","TWO","THREE");
printUs("FOUR","FIVE");
}
private static void printUs(String ... args) {
System.out.println("Var args method");
for (int i = 0;i<args.length;i++) {
System.out.println( args[i] );
}
}
private static void printUs(String arg1,String arg2) {
System.out.println("Specific two argument method ");
System.out.println( arg1 );
System.out.println( arg2 );
}
}
It produces the following output
Var args method ONE TWO THREE Specific two argument method FOUR FIVE
How about that for a main!
The args parameter is handled just like an array.
You can see if there is method specifying an explicit number of parameters of the requested type, it takes precedence
Of course you could also use the new for loop
private static void printUs(String ... args) {
System.out.println("Var args method");
for (String s: args) System.out.println(s);
}
How does that extend to other types? Do you have to use Object… for non-homogenic varargs? (first thing that comes to mind is printf like format)? Do integral types have to be wrapped?