Java Reference
In-Depth Information
That is, when running the program
PassByValue
, the block of instructions in
the
main
procedure is executed as follows:
-
Local variable
x
of
main
is assigned to value 5,
-
Function
F
is called with basic expression
x
that is evaluated to 5 and passed
by value to
F
(expression/argument binding),
-
Local variable
x
of
F
(not of
main
) is assigned to 3, and the message
Before
exiting F, value of x:3.0
is displayed,
-
Function
F
is completed, and its local allocated memory is removed from the
function stack,
-
Message
value of x:5.0
is displayed from the last instruction of the
main
procedure.
In a similar way, swapping two integer variables cannot be achieved by the
following erroneous code since Java is pass-by-value:
public void badSwap(int var1, int var2)
{
int temp = var1;
var1 = var2;
var2 = temp;
} // at the end of this block, var1 and var2 keeps their original value
Loosely speaking, functions usually do not change the
calling
environment.
Function
y=F(x)
returns a result that is taken into account in the calling
environment. There are of course different ways for functions and procedures
to alter the calling environment. This bears the name of
side-effect
functions.
3.4.3 Side-effects of functions: Changing the calling
environment
We have previously seen that functions can share the static (class) variables.
We gave an example where the overall number of function calls was updated
every time a function was called. This is one example of a function side-effect
of calling functions: Changing the global environment. Let us give yet another
simple example to illustrate this point:
Program 3.8
Toy example for illustrating how functions can change the
environment
class
FunctionSideEffect
{
static int
x=0;
static void
F()
Search WWH ::
Custom Search