Java Reference
In-Depth Information
You must always do things like this when dealing with command-line arguments.
Otherwise, your programs crash with
ArrayIndexOutOfBoundsException
errors when-
ever the user supplies fewer command-line arguments than you were expecting.
If at least one argument is passed, the
for
loop iterates through all the strings stored in
the
arguments
array (lines 6-8).
Because all command-line arguments are passed to a Java application as
String
objects,
you must convert them to numeric values before using them in any mathematical expres-
sions. The
parseInt()
class method of the
Integer
class takes a
String
object as input
and returns an
int
(line 7).
If you can run Java classes on your system with a command line, type the following:
java Averager 1 4 13
You should see the following output:
Sum is: 18
Average is: 6.0
Different Arguments
When you work with Java's class library, you often encounter classes that have numerous
methods with the same name.
Two things differentiate methods with the same name:
The number of arguments they take
n
The data type or objects of each argument
n
These two things are part of a method's signature. Using several methods with the same
name and different signatures is called
overloading
.
Method overloading can eliminate the need for entirely different methods that do essen-
tially the same thing. Overloading also makes it possible for methods to behave differ-
ently based on the arguments they receive.
When you call a method in an object, Java matches the method name and arguments to
choose which method definition to execute.
To create an overloaded method, you create different method definitions in a class, each
with the same name but different argument lists. The difference can be the number, the