Java Reference
In-Depth Information
double result = (b*h)/2;
return result;
}
The method getArea() declares in its paramenter list two variables of
type double, named b and h. While the method call references, in paren-
theses, the arguments base and height, whose values are passed to
getArea().
Programmers note:
The term “argument” relates to elements in the method's call, while
the term “parameter” refers to the elements listed in the method's dec-
laration. In other words, a value passed to a method is an argument
from the viewpoint of the caller, and a parameter from the viewpoint
of the method itself.
Data is passed to a method in the same order in which the arguments
are listed in the call. The method's parameter list defines this order. In the
case of the method getArea() previously listed, the first argument in the
method's call, the variable base, becomes the parameter b declared in the
method's header. While the second argument referenced in the call, the
variable height, becomes the variable h in the method.
The value returned by a method is associated with its name. This ex-
plains why the variable contained in a method's return statement can be
of local scope. Also notice that a method returns a single value to the
caller.
Methods and Global Variables
You have learned that the scope of a Java variable is the block in which it is
declared. Since a method's body is defined within a block, a variable de-
clared inside this block has local scope . Sometimes we say that method vari-
ables have method scope . For example:
public static double getArea(double b, double h)
{
double result = (b * h) / 2;
return result;
}
The scope of the variable result is the getArea() method. Data elements
declared outside the methods of a class have class (or global) scope . The
fact that methods can access global data provides a simple mechanism
whereby a method can return more than one result to the caller.
Search WWH ::




Custom Search