Java Reference
In-Depth Information
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
running 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
numbers, you must convert the string representations of the numbers to values of a
number type or types.
The Method
main
Has an Array Parameter
The heading for the
main
method of a program is as follows:
public static void
main(String[] args)
The identifier
args
is a parameter for an array of base type
String
. The details are
explained in the text.