Java Reference
In-Depth Information
In
Figure 5-3
you have the definition of a method
mean()
. The definition of this method appears within
the definition of the class
MyClass
. You can see that the method has two parameters,
value1
and
value2
,
both of which are of type
double
. The parameter names are used to refer to the arguments
3.0
and
5.0
,
respectively, within the body of the method when it is called by the statement shown. Because this method
has been defined as
static
, you can call it only using the class name.
When you call the
mean()
method from another method (from
main()
in this case, but it could be from
some other method), the values of the arguments that you pass are the initial values assigned to the corres-
ponding parameters before execution of the body of the method begins. You can use any expression you
like for an argument when you call a method, as long as the value it produces is of the same type as the
corresponding parameter in the definition of the method. With the method
mean()
, both parameters are of
type
double
, so both argument values must always be of type
double
.
The method
mean()
defines the variable
result
, which exists only within the body of the method. This
variable is newly created each time you execute the method and is destroyed when execution of the method
ends. All the variables that you declare within the body of a method are local to the method, and are only
around while the method is being executed. Variables declared within a method are called
local variable
s
because they are local to the method. The scope of a local variable is as I discussed in Chapter 2, from the
point at which you declare it to the closing brace of the immediately enclosing block, and local variables
are not initialized automatically. If you want your local variables to have initial values, you must supply the
initial value when you declare them.
How Argument Values Are Passed to a Method