|
Example:
void f(int a)
{ <--- variable a exists because f(a) has created a
..... location where variable a exists ....
} <--- variable a is "destroyed"
void main(String[] args)
{
....
f(a); <---- variable a is created and then f() is invoked
....
}
|
|
Example:
void f(....)
{
int x; // variable x begins to exist
x = 1;
int y; // variable y begins to exist
y = 2;
} <----- variables x and y are destroyed
|
|
|
public class Behavior
{
public static int count = 0;
public static void f(int a)
{
int b; // Local variable
b = a + 100;
if ( a == 0 )
return;
else
f(a-1);
System.out.println(" a = " + a + " b = " + b);
}
public static void main(String[] args)
{
f(3);
}
}
|
Output:
a = 1 b = 101 a = 2 b = 102 a = 3 b = 103 |
How is the program executed:
main: +--> f(a = 3) +--> f(a = 2) +--> f(a = 1) +--> f(a = 0)
/ / / / |
f(3) - b = 100 + 3 / b = 100 + 2 / b = 100 + 1 / | (return)
/ / / |
f(a-1) ---- f(a-1) ---- f(a-1) ---- |
|
print(a,b) (1, 101) <--+
|
print(a,b) (2, 102) <--+
|
print(a,b) (3, 103) <--+
|
<---------------+
|
|
Example:
void f( ... )
{
}
void main( .... )
{
....
f( ... ); // f is invoked and becomes active
During the entire time that f() is ACTIVE
the method f() will not be invoked again !
}
|
|
|
Example:
public class Behavior
{
public static int count = 0;
/* ---------------------------------------
A recursive method
--------------------------------------- */
public static void f(int a)
{
int b; // Local variable
b = a + 100;
if ( a == 0 )
return;
else
f(a-1);
System.out.println(" a = " + a + " b = " + b);
}
public static void main(String[] args)
{
f(3);
}
}
|
Notice that f() was invoked while f() is active:
main: +--> f(a = 3) +--> f(a = 2) +--> f(a = 1) +--> f(a = 0)
/ / / / |
f(3) - b = 100 + 3 / b = 100 + 2 / b = 100 + 1 / | (return)
/ / / |
f(a-1) ---- f(a-1) ---- f(a-1) ---- |
|
print(a,b) (1, 101) <--+
|
print(a,b) (2, 102) <--+
|
print(a,b) (3, 103) <--+
|
<---------------+
|
|