Java Reference
In-Depth Information
Thus, within a method, there is no need to specify the object a second time. This means
that
fuelcap
and
mpg
inside
range( )
implicitly refer to the copies of those variables found
in the object that invokes
range( )
.
Returning from a Method
In general, there are two conditions that cause a method to return—first, as the
range(
)
method in the preceding example shows, when the method's closing curly brace is en-
countered. The second is when a
return
statement is executed. There are two forms of
re-
turn
—one for use in
void
methods (those that do not return a value) and one for returning
values. The first form is examined here. The next section explains how to return values.
In a
void
method, you can cause the immediate termination of a method by using this
form of
return
:
return ;
When this statement executes, program control returns to the caller, skipping any remaining
code in the method. For example, consider this method:
Here, the
for
loop will only run from 0 to 5, because once
i
equals 5, the method returns.
It is permissible to have multiple
return
statements in a method, especially when there are
two or more routes out of it. For example: