Java Reference
In-Depth Information
also called
formal parameters.
) The value that is plugged in for the parameter is called an
argument
.
2
We have already used arguments with predefined methods. For example, the
string
"Hello"
is the argument to the method
println
in the following method invocation:
argument
System.out.println("Hello");
Display 4.4 contains the definition of a method named
setDate
that has the three
parameters
newMonth
,
newDay
, and
newYear
. It also contains the definition of a method
named
monthString
that has one parameter of type
int
.
The items plugged in for the parameters are called
arguments
and are given in
parentheses at the end of the method invocation. For example, in the following call
from Display 4.4, the integers
6
and
17
and the variable
year
are the arguments
plugged in for
newMonth
,
newDay
, and
newYear
, respectively:
date.setDate(6, 17, year);
When you have a method invocation like the preceding, the argument (such as
6
) is
plugged in for the corresponding formal parameter (such as
newMonth
)
everywhere that the
parameter occurs in the method definition.
After all the arguments have been plugged in for
their corresponding parameters, the code in the body of the method definition is executed.
The following invocation of the method
monthString
occurs within the definition
of the method
setDate
in Display 4.4:
month = monthString(newMonth);
The argument is
newMonth
, which is plugged in for the parameter
monthNumber
in the
definition of the method
monthString
.
Note that each of the formal parameters must be preceded by a type name, even if there is
more than one parameter of the same type. Corresponding arguments must match the type
of their corresponding formal parameter, although in some simple cases, an automatic type
cast might be performed by Java. For example, if you plug in an argument of type
int
for a
parameter of type
double
, Java automatically type casts the
int
value to a value of type
double
. The following list shows the type casts that Java automatically performs for you. An
argument in a method invocation that is of any of these types is automatically type cast to
any of the types that appear to its right if that is needed to match a formal parameter.
3
byte
—>
short
—>
int
—>
long
—>
float
—>
double
2
Some programmers use the term
actual parameters
for what we are calling
arguments.
3
An argument of type
char
is also converted to a matching number type, if the formal parameter is
of type
int
or any type to the right of
int
in our list of types.