6.8. Methods Accepting a Variable Number of Arguments

You can write a method so that it will accept an arbitrary number of arguments when it is called, and the arguments that are passed do not need to be of the same type. The reason I have waited until now to mention this is that understanding how this works depends on having an understanding of the role of the Object class. You indicate that a method will accept a variable number of arguments by specifying the last parameter as follows:

Object ... args

The method can have zero or more parameters preceding this, but this must be last for obvious reasons. The ellipsis (three periods) between the type name Object and the parameter name args enables the compiler to determine that the argument list is variable. The parameter name args represents an array of type Object[], and the argument values are available in the elements of the array as type Object. Within the body of the method, the length of the args array tells you how many arguments were supplied.

Let's consider a very simple example to demonstrate the mechanism. Suppose you want to implement a static method that will accept any number of arguments and output the arguments to the command line—whatever they are. You could code it like this:

public static void printAll(Object ... args) {
  for(Object arg : args) {
    System.out.print("  "+arg);

The arguments can be anything at all. Values of primitive types will be autoboxed because the method expects reference ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.