img
Try executing this program, as shown here:
java CommandLine this is a test 100 -1
When you do, you will see the following output:
args[0]:
this
args[1]:
is
args[2]:
a
args[3]:
test
args[4]:
100
args[5]:
-1
REMEMBER  All command-line arguments are passed as strings. You must convert numeric values
EMEMBER
to their internal forms manually, as explained in Chapter 16.
Varargs: Variable-Length Arguments
Beginning with JDK 5, Java has included a feature that simplifies the creation of methods
that need to take a variable number of arguments. This feature is called varargs and it is
short for variable-length arguments. A method that takes a variable number of arguments
is called a variable-arity method, or simply a varargs method.
Situations that require that a variable number of arguments be passed to a method are
not unusual. For example, a method that opens an Internet connection might take a user
name, password, filename, protocol, and so on, but supply defaults if some of this information
is not provided. In this situation, it would be convenient to pass only the arguments to
which the defaults did not apply. Another example is the printf( ) method that is part of
Java's I/O library. As you will see in Chapter 19, it takes a variable number of arguments,
which it formats and then outputs.
Prior to JDK 5, variable-length arguments could be handled two ways, neither of which
was particularly pleasing. First, if the maximum number of arguments was small and
known, then you could create overloaded versions of the method, one for each way the
method could be called. Although this works and is suitable for some cases, it applies to
only a narrow class of situations.
In cases where the maximum number of potential arguments was larger, or unknowable,
a second approach was used in which the arguments were put into an array, and then the
array was passed to the method. This approach is illustrated by the following program:
// Use an array to pass a variable number of
// arguments to a method. This is the old-style
// approach to variable-length arguments.
class PassArray {
static void vaTest(int v[]) {
System.out.print("Number of args: " + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home