Chapter 6. Value Methods
Some of the methods we have used, like the Math
methods, return values. But all the methods we have written so far have been void
; that is, they don’t return values. In this chapter, we’ll write methods that return values, which we call value methods.
Return Values
When you invoke a void method, the invocation is usually on a line all by itself. For example, here is the countup
method from “Recursive Methods”:
public
static
void
countup
(
int
n
)
{
if
(
n
==
0
)
{
System
.
out
.
println
(
"Blastoff!"
);
}
else
{
countup
(
n
-
1
);
System
.
out
.
println
(
n
);
}
}
And here is how it is invoked:
countup
(
3
);
System
.
out
.
println
(
"Have a nice day."
);
On the other hand, when you invoke a value method, you have to do something with the return value. We usually assign it to a variable or use it as part of an expression, like this:
double
error
=
Math
.
abs
(
expected
-
actual
);
double
height
=
radius
*
Math
.
sin
(
angle
);
Compared to void methods, value methods differ in two ways:
They declare the type of the return value (the return type);
They use at least one
return
statement to provide a return value.
Here’s an example: calculateArea
takes a double
as a parameter and returns the area of a circle with that radius:
public
static
double
calculateArea
(
double
radius
)
{
double
result
=
Math
.
PI
*
radius
*
radius
;
return
result
;
}
As usual, this method is public
and static
. But in the place where we are used to seeing void
, we see double
, which means that the return value from this method is a double ...
Get Think Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.