Java Reference
In-Depth Information
8.4 Command-Line Arguments
SR 8.17 A command-line argument is data that is included on the command line
when the interpreter is invoked to execute the program. Command-line
arguments are another way to provide input to a program. They are
accessed using the array of strings that is passed into the main method
as a parameter.
SR 8.18 //------------------------------------------------------
// Prints the sum of the string lengths of the first
// two command line arguments.
//------------------------------------------------------
public static void main (String[] args)
{
System.out.println (args[0].length() +
args[1].length());
}
SR 8.19 //------------------------------------------------------
// Prints the sum of the first two command line
// arguments, assuming they are integers.
//------------------------------------------------------
public static void main (String[] args)
{
System.out.println (Integer.parseInt(args[0])
+ Integer.parseInt(args[1]));
}
8.5 Variable Length Parameter Lists
SR 8.20 A Java method can be defined to accept a variable number of param-
eters by using ellipses (...) in the formal parameter list. When a set of
values is passed to the method, they are automatically converted to an
array. This allows the method to be written in terms of array processing
without forcing the calling method to create the array.
SR 8.21 public int distance ( int ... legs)
{
int sum = 0;
for ( int leg : legs)
{
sum += leg;
}
return sum;
}
SR 8.22 double travelTime ( int speed, int ... legs)
{
int sum = 0;
Search WWH ::




Custom Search