Tuesday, September 11, 2007

Varargs Facility

Variable arity methods, sometimes referred to as varargs methods, accept an arbitrary set of arguments. Prior to JDK 5.0, if you wanted to pass an arbitrary set of arguments to a method, you needed to pass an array of objects. Furthermore, you couldn't use variable argument lists with methods such as the format method of the MessageFormat class or the new to JDK 5.0 printf method of PrintStream to add additional arguments for each formatting string present.



JDK 5.0 adds a varargs facility that's a lot more flexible. To explore the varargs facility, let's look at a JDK 5.0 version of one of the printf methods in the PrintStream class:

public PrintStream printf(String format, Object... args)

Essentially, the first argument is a string, with place holders filled in by the arguments that follow. The three dots in the second argument indicate that the final argument may be passed as an array or as a sequence of arguments.


The number of place holders in the formatting string determines how many arguments there need to be. For example, with the formatting string "Hello, %1s\nToday is %2$tB %2$te, %2$tY" you would provide two arguments: the first argument of type string, and the second of type date. Here's an example:

import java.util.*;

public class Today {
public static void main(String args[]) {
System.out.printf(
"Hello, %1s%nToday is %2$tB %2$te, %2$tY%n",
args[0], new Date());
}
}
Provided that you pass in an argument for the name, the results would be something like the following:

> java Today Ed
Hello, Ed
Today is October 18, 2005

No comments: