Java Reference
In-Depth Information
Returning from a Method
A method concludes when it reaches the return keyword. At this point, exe-
cution returns to the caller at the statement that follows the call. A return
statement can include an expression, optionally enclosed in parentheses,
which represents the value returned to the caller. The method
getAverage(), listed previously, has the following statement:
return sum / intArray.length;
The value returned by a method must always match the return type de-
fined in its declaration. Parentheses can optionally be used to clarify the
calculations of a returned value, as follows:
return (sum / intArray.length);
If the method's return type is void, then no value can follow the return
statement. For example, a method with void return type concludes execu-
tion with the statement:
return;
If you do not code a statement, the method concludes at the line that
precedes the closing roster. In this case, programmers say that the
method “falls off the edge.” A method can also return a constant to the
caller, as in the following example:
public static double getPi()
{
return 3.141592653589793;
}
In the preceding example, the method getPi() returns the constant PI
to the calling routine.
Programmers note:
A method without a return statement does not produce a compiler er-
ror. However, an explicit return is better, since it leaves no doubt
about the programmer's intention.
The return statement can appear anywhere in the method body. A sin-
gle method can contain several return statements. Each return statement
can be associated with a different value. This is the case in the isOdd()
method:
public static boolean isOdd(int aValue)
{
Search WWH ::




Custom Search