Java Reference
In-Depth Information
tion body, and, thus, the function call, and yields the value of the expression as
the result of the call.
Since execution of a function body must terminate with execution of a return
statement, a return statement is usually the last statement in the function body.
However, return statements may appear in other places as well, see e.g. Fig. 2.3.
Suppose the call smallest(2, 6, 6) is to be evaluated. Then, parameter b
is 2 , c is 6 , and d is 6 . Therefore, the condition of the first if-statement is true,
and the then-part of that if-statement, return b; , is executed. This terminates
execution of the function body and yields 2 as the value of the function call.
Executing a function call
Earlier, we gave a list of four steps for executing a procedure call. The only
difference in executing a function call is that the value of the expression in the
return statement whose execution terminates the call has to be returned as the
value of the function. For purposes of completeness, we summarize here the
steps in executing a function call:
1. Draw the parameters of the function, as variables.
2. Evaluate the arguments of the call and store their values in the corre-
sponding parameters of the function.
3. Execute the statements of the body of the function.
4. To execute return e; , evaluate expression e , erase the parameters of the
method, and use the value of e as the value of the function call.
2.3.7
Local variables
A local variable is a variable that is declared within a method body. The scope
of a variable is the area of a program where it can be used. The scope of a local
variable is the sequence of statements that follows its declaration, up until the
end of the block in which it is declared. The declaration of a local variable has
this form:
Activity
2-3.1
type variable-name ;
Its initial value is unknown, and the variable cannot be referenced until a value
has been stored in it. An initializing declaration of a local variable has this form:
/** Using g , draw a triangle that fits in the rectangle drawn by drawRect(x, y, w, h) .
One side is the base of the rectangle; the other two sides meet at pixel (x+w/2, y) . */
public void drawTriangle(Graphics g, int x, int y, int w, int h) {
g.drawLine(x, y + h, x + w, y + h);
g.drawLine(x, y + h, x +w/2, y);
g.drawLine(x + w, y + h, x +w/2, y);
}
Figure 2.4:
Drawing a triangle
Search WWH ::




Custom Search