Java Reference
In-Depth Information
Arguments for the Method
main
★
The heading for the
main
method of a program looks as if it has a parameter for an
array of base type of
String
:
public
static
void
main(String[] args)
The identifier
args
is in fact a parameter of type
String[]
. Since
args
is a parameter,
it could be replaced by any other non-keyword identifier. The identifier
args
is tradi-
tional, but it is perfectly legal to use some other identifier.
We have never given
main
an array argument, or any other kind of argument,
when we ran any of our programs. So, what did Java use as an argument to plug in for
args
? If no argument is given when you run your program, then a default empty
array of strings is automatically provided as a default argument to
main
when you run
your program.
It is possible to run a Java program in a way that provides an argument to plug in
for this array of
String
parameters. You do not provide it as an array. You provide any
number of string arguments when you run the program, and those string arguments
will automatically be made elements of the array argument that is plugged in for
args
(or whatever name you use for the parameter to
main
). This is normally done by run-
ning the program from the command line of the operating system, like so:
java YourProgram Do Be Do
This will set
args[0]
to
"Do"
,
args[1]
to
"Be"
,
args[2]
to
"Do"
, and
args.length
to
3
. These three indexed variables can be used in the method
main
, as in the following
sample program:
public class
YourProgram
{
public static void
main(String[] args)
{
System.out.println(args[1] + " " + args[0]
+ " " + args[1]);
}
}
If the above program is run from the command line as follows,
java YourProgram Do Be Do
the output produced by the program will be
Be Do Be
Be sure to note that the argument to
main
is an array of
strings.
If you want num-
bers, you must convert the string representations of the numbers to values of a number
type or types.