Java Reference
In-Depth Information
these numbers is a floating-point number—say,
double
. Because the larger number is of
type
double
, the method's data type is also
double
. Let's name this method
larger
.
The only thing you need to complete this method is the body of the method. Thus,
following the syntax of a method, you can write this method as follows:
public static double
larger(
double
x,
double
y)
{
double
max;
if
(x >= y)
max = x;
else
max = y;
return
max;
}
Note that the method
larger
uses an additional variable
max
(called a local declara-
tion, where
max
is a variable local to the method
larger
). Figure 7-1 describes the
various parts of the method
larger
.
Formal
parameters
Method
return type
Method
name
Modifiers
Method
heading
p
ublic static double
larger(
double
x,
double
y)
{
double
max;
Local
variable
Formal parameters
list
if
(x >= y)
max = x;
else
max = y;
Method
body
Method
return
value
return
max;
}
FIGURE 7-1
Various parts of the method
larger
Suppose that
num
,
num1
, and
num2
are
int
variables. Also suppose that
num1 = 45.75
and
num2 = 35.50
. Figure 7-2 shows various calls to the method
larger
.
Search WWH ::
Custom Search