Java Reference
In-Depth Information
Statement
The return type specified in the method header can be a primitive type, class
name, or the reserved word void . When a method does not return any value, void
is used as the return type, as is always done with the main method. The setFaceValue
method of the Die class also has a return type of void .
A method that returns a value must have a return statement. When a return
statement is executed, control is immediately returned to the statement in the
calling method, and processing continues there. A return statement consists of
the reserved word return followed by an expression that dictates the value to be
returned. The expression must be consistent with the return type in the method
header.
The getFaceValue method of the Die class returns an int value that represents
the current value of the die. The roll method does the same, returning the new
value to which faceValue was just randomly set. The toString method returns
a String object.
A method that does not return a value does not usually contain a
return statement. The method automatically returns to the calling
method when the end of the method is reached. Such methods may
contain a return statement without an expression.
It is usually not good practice to use more than one return state-
ment in a method, even though it is possible to do so. In general, a method should
have one return statement as the last line of the method body, unless that makes
the method overly complex.
The value that is returned from a method can be ignored in the calling method.
For example, in the main method of the RollingDice class, the value that is returned
The
return
KEY CONCEPT
The value returned from a method
must be consistent with the return
type specified in the method header.
Return Statement
return
;
Expression
A return statement consists of the return reserved word fol-
lowed by an optional Expression. When executed, control is immedi-
ately returned to the calling method, returning the value defined by
Expression.
Examples:
return ;
return distance * 4;
 
 
Search WWH ::




Custom Search