Java Reference
In-Depth Information
accessed from outside the function bodies.
Suppose now that we would like to count the number of times a given function
is called. We need to declare a kind of persistent variable that we can attach
to the class encapsulating the function: These kinds of persistent variables are
called
static
variables. Using static variables, it becomes easy, say, to count the
overall number of function calls as illustrated by the following code:
Program 3.5
An example using a static (class) variable
class
StaticVariable
{
static int
nbfunccalls=0;
static int
square(
int
x)
{
nbfunccalls++;
return
x
∗
x;
}
static boolean
isOdd(
int
p)
{
nbfunccalls++;
if
( ( p%2)==0)
return false
;
else return true
;
}
static double
distance(
double
x,
double
y)
{
double
result ;
nbfunccalls++;
if
(x
>
y) result=x
−
y;
else
result=y
−
x;
return
result ;
}
static void
display(
double
x,
double
y)
{
nbfunccalls++;
System . out . println (
"("
+x+
","
+y+
")"
);
}
public static void
main ( String [ ]
args )
{
FunctionDeclaration . display (3 ,2) ;
display(square(2) ,distance (5 ,9)) ;
int
p=123124345;
if
(isOdd(p) )
System . out . println (
"p is odd"
);
else
System . out . println (
"p is even"
);
System . out . println (
"Total number of function calls:"
+
nbfunccalls) ;
}
}
Running this program, we get the following message after completion:
Total number of function calls:4
Search WWH ::
Custom Search