<< Chapter < Page | Chapter >> Page > |
main
method calls the method
printMax
;
the actual parameters are two integer literals.printMax
is allocated,
and the actual parameters are used to initialize the formal parameters
a
and
b
.max
is allocated but not initialized.maximum
is called; the actual parameters are the
values of
a
and
b
,
which are the formal variables of method
printMax
.maximum
. (There are now
three activation in the stack.) The new activation record includesmemory for the formal parameters
a
and
b
; note that these are
new parameters not at all related to the formal parameters of the same namesin the previous method
printMax
because those parameters are hidden.maximum
executes its body and returns a value.
Just before it returns, select the tab
Call Tree
above the graphic display;
the sequence of calls from
main
to
printMax
and then
maximum
is displayed.
Select
Theater
to return to the animated display.printMax
.max
and printed.printMax
completes its execution, its activation record
is deallocated.
Note: In a call to a static method, the name of the
class in which it is defined can be given as in the call to
maximum
.
Since the method is defined in the same class as the call,the class name need not be given, as shown in the call to
printMax
.
Exercise Write a program to compute the maximum of six values using as few statements as possible.
Concept Recursion occurs when method calls itself. There is nothing at all mysterious about recursion!Each call simply creates a new activation record on the stack. However, to ensure that the recursive calls terminate,eventually, some call of the method should return without invoking itself once again.
Program: Method04.java
// Learning Object Method04
// recursionpublic class Method04 {
static int factorial (int n) { if (n <= 1)
return 1; else
return n * factorial(n-1); }
public static void main(/*String[] args*/) { System.out.println(factorial(5));
}}
The standard example of a recursive method is one that computes the factorial function:
The recursion is terminated by defining for .
main
method calls the method
factorial
with the actual parameter 5. This creates an activation record with
the formal parameter
n
initialized to 5.factorial
is called again, this time with the actual
parameter equal to
.n
.factorial
is called with actual parameter 1.
This call creates a new activation record as usual, but does notcause
factorial
to be invoked again. Instead,
the value 1 is returned and the activation record is deallocated.Just before the method returns, select the tab
Call Tree
above the graphic display;
the sequence of calls from
main
to the sequence of recursive calls is displayed.
Select
Theater
to return to the animated display.factorial
.main
method and printed.Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?