A method communicates back to the caller by returning a value.
The type of value returned by a method (i.e. the return-type) is specified when the method is defined.
A method does not have to return a value. In these cases, the return-type
- Methods can return at most one value.
- A method returns to the caller by executing a
- Methods can have multiple
returnstatements. (Although structured programming purists don't like this.)
- A method returns to the method that called it. (unless it
The syntax of the
returnstatement is as follows.return; //used when the return-type of the method is void return EXPR; EXPR is evaluated. The result of the evaluation must match the return-type of the method. If it doesn't, then explicit type-cast is needed. For example, if the return-type of the method is int , then return (int)3.14; will cause the 3.14 double to be converted to an int; therefore, the calling method will be returned the value 3. Optionally, the return EXPR can be enclosed in parens. return (EXPR); return (3.14); or return 3.14; return (i + 3 * j); or return i + 3 * j; return (i > 4); or return i > 4;
If a method returns a value, then it is the caller's responsibility to examine the return value.
If a methods's return-type is
returnstatements, if any, cannot have any expressions.