Java Reference
In-Depth Information
Java syntax: procedure return statement
return
;
Example
:
return
;
Purpose
: Terminate execution of a proce-
dure call.
Java syntax: function return statement
return
expression
;
Example
:
return
b+c;
Purpose
: Terminate execution of a function
call and use the value of the
expression
as the
value of the function call.
2.3.5
The return statement
When a procedure is called, the statements in the procedure body are executed
one at a time, in the order in which they appear. However, it is occasionally
advantageous to terminate execution of the body before the last statement has
been executed. We use the return statement for this purpose. It has this form:
Activity
2-3.4
return
;
Execution of a return statement terminates execution of the procedure body
and, hence, of the procedure call. Once a return statement is executed, no more
statements in the procedure body are executed.
Procedure
printSmallest
in Fig. 2.2 contains two return statements.
Suppose the call
printSmallest(5, 6, 6);
is to be executed. Then, parameter
b
will be
5
,
c
will be
6
, and
d
will be
6
. Therefore, the condition of the first if-
statement will be
true
,
b
will be printed, and execution of the return statement
will terminate execution of the procedure body and, hence, of the procedure call.
The second if-statement and the last print statement are not executed.
Consider a call
printSmallest(6, 2, 5);
. In this case, parameter
b
will be
6
,
c
will be
2
, and
d
will be
5
. Therefore, the condition of the first if-statement is
/**
Print the smallest of
b
,
c
, and
d */
public static void
printSmallest(
int
b,
int
c,
int
d) {
if
(b <= c && b <= d) {
System.out.println(b);
return
;
}
// {
the smallest is
cord }
if
(c <= d) {
System.out.println(c);
return
;
}
// {
the smallest is
d }
System.out.println(d);
}
Figure 2.2:
A procedure with
return
statements
Search WWH ::
Custom Search