The
|
| BASIC |
Almost all computation in Java is done inside methods, and each method
has a type. When a method executes a return
statement, control returns to the code that "called" the method (more
accurately, to the code that sent a message to the object or class containing
that method). When the method returns, the value specified by the return
statement is used in place of the call. For example, the statement
x = Math.sqrt(y) + 1;
sends the message sqrt(y) to the Math class, gets
a double result (the sqrt method has type double),
adds 1 to it, and assigns this sum to x.
There are two forms of the return statement:
return expression;
return;
The first form computes and returns the value of the expression.
This value must either be the same type as the type of the method, or a must
be a type that can be assigned to the type of the method (for example, if the
method returns a double, the return statement may
compute an int, since an int value can be assigned
to a double variable).
Methods may also have the type void. This means that the method
does not return a value and cannot be used in an expression; it can only
be used as a "statement." For example, the method System.out.println
is of type void. Methods of type void must use the
second form of the return statement.