Java Reference
In-Depth Information
10.9.
return
A
return
statement terminates execution of a method and returns to the
invoker. If the method returns no value, a simple
return
statement will
do:
return;
If the method has a return type, the
return
must include an expression of
a type that could be assigned to the return type. For example, if a meth-
od returns
double
, a
return
could have an expression that was a
double
,
float
, or integer:
protected double nonNegative(double val) {
if (val < 0)
return 0; // an int constant
else
return val; // a double
}
A
return
can also be used to exit a constructor. Since constructors do not
specify a return type,
return
is used without a value. Constructors are
invoked as part of the
new
process that, in the end, returns a reference
to a new object, but each constructor plays only a part of that role; no
constructor "returns" the final reference.