Java Reference
In-Depth Information
false , so execution of the first if-statement is finished. The condition of the sec-
ond if-statement is true , so the value of c , or 2 , will be printed, and execution
of the return statement will terminate execution of the procedure body and, thus,
of the procedure call.
Using an assertion to help the reader
The reader of a program can benefit from the insertion of comments at judi-
ciously chosen places in the program to alert them to what is true about the vari-
ables at those places. For example, after the first if-statement in this body, it may
help to indicate that b is not the smallest parameter. Such a description of the
variables is called an assertion because we are asserting that it is true at a point
of execution of the program. By convention, we enclose assertions in curly
braces (note that the curly braces are not part of the assertion). The braces alert
the reader to the fact that this comment is an assertion about the values of the
variables, not a specification or command to do something.
Style Note
13.2, 13.2.2:
The function body
The procedure in Fig. 2.2 prints the smallest of its three parameters. In many pro-
grams, it may be useful to use the smallest of three values in a later calculation,
rather than print it, and in these applications, procedure printSmallest is use-
less. Instead, we need a function that calculates the smallest of three values and
returns it for later use. This function is given in Fig. 2.3.
A function must return a value. Therefore, execution of a function must ter-
minate by executing a return statement of the form
return expression ;
where the type of the expression is the same as (or narrower than) the type of the
result of the function. Execution of such a return statement terminates the func-
/** = smallest of b , c , and d . */
public static int smallest( int b, int c, int d) {
if (b <= c && b <= d) {
return b;
// {the smallest is c or d}
if (c < d) {
return c;
// {the smallest is d}
return d;
Figure 2.3:
A function that returns the smallest of its parameters
Search WWH ::

Custom Search