Java Reference
In-Depth Information
ods can use the same name for a parameter. For example, we can define the fol-
lowing procedure inside class PrintExample (place it either before or after
method print3 ), even though it uses the same parameter names as print3 :
/** Print b+c */
public static void printSum( int b, int c) {
System.out.println(b + c);
Within the body of method print3 , b refers to the parameter declared in the
definition of print3 ; within the body of method printSum , b refers to the
parameter declared in the definition of printSum . The variables are not related.
Executing a procedure call
We now discuss how a procedure call is executed. This is necessarily a high-level
explanation. Later, we will give a lot more detail, giving a model that explains
precisely how Java method calls work.
Suppose we have two variables, x and y , with values 20 and 5 . We draw
these variables as boxes, with the names to the left and the values inside:
x 20
In this situation, execution of the procedure call
PrintExample.print3(x, 2 * y);
proceeds as follows:
1. Draw the parameters of the method, as variables.
2. Evaluate the arguments of the call and store their values in the corre-
sponding parameters of the procedure.
3. Execute the statements of the body of the procedure.
4. Erase the parameters of the method.
In this case, argument x corresponds to parameter b and argument 2*y cor-
responds to parameter c . Therefore, the first and second steps result in this state:
b 20
c 10
In performing step three, the statements are executed one by one, beginning
with the first. If a parameter name is used, the value of the parameter is used in
its place. In this case, execution of the method body results in three values being
printed on three separate lines: 20 , 10 , and 30 . Finally, the parameters are erased.
It is important that you can execute a procedure call yourself, as just shown.
As you already know, a method body can contain calls on other methods. In
fact, it is typical for one method to contain several calls on others. As an exam-
Search WWH ::

Custom Search