Java Reference
In-Depth Information
The arguments can be anything. Values of primitive types are autoboxed because the method expects ref-
erence arguments. The loop outputs the string representation of each of the arguments on a single line, the
string being produced by invoking the toString() method for whatever the argument is. Let's see it work-
ing.
TRY IT OUT: Displaying Arguments of any Type
Here's a program that exercises the printAll() method:
public class TryVariableArgumentList {
public static void main(String[] args) {
printAll( 2, "two", 4, "four", 4.5, "four point five");
// Six
arguments
printAll();
// No
arguments
printAll(25, "Anything goes", true, 4E4, false);
// Five
arguments
}
public static void printAll(Object ... args) {
for(Object arg : args) {
System.out.print(" " + arg);
}
System.out.println();
}
}
TryVariableArgumentList.java
This program produces the following output:
2 two 4 four 4.5 four point five
25 Anything goes true 40000.0 false
How It Works
You can see from the output that the printAll() method works as advertised and accepts an arbitrary
number of arguments. The first call of the printAll() method mixes arguments of type int , type
String , and type double . Each numerical value is converted to an object of the corresponding wrapper
class type by a boxing conversion that the compiler inserts. The output strings are then produced by calls
to the toString() method for the objects, also expedited by the compiler. The second call to the method
results in an empty line. The last line of output shows that autoboxing works with boolean values as well
as values of the other primitive types.
The standard class libraries use the variable argument list capability to define the printf() method in
the java.io.PrintStream class. This method produces formatted output for an arbitrary sequence of
Search WWH ::




Custom Search