Java Reference
In-Depth Information
Suppose you call the
getNumber()
method as follows:
int w = 100;
int s = getNumber(w, w);
/* What is value of s at this point: 200, 8, 10 or something else? */
When the
getNumber()
method returns, what value will be stored in the variable
s
? Note that both parameters
to the
getNumber()
method are passed by reference and you pass the same variable,
w
, for both parameters in your
call. When the
getNumber()
method starts executing, the formal parameters
x
and
y
are aliases to the same actual
parameter
w
. When you use
w
,
x
, or y, you are referring to the same data in memory. Before adding
x
and
y
, and storing
the result in the
sum
local variable, the method sets the value of
y
to
5
, which makes
w
,
x
, and
y
all have a value of
5
.
When
x
and
y
are added inside the method, both x and
y
refer to the value
5
. The
getNumber()
method returns
10
.
Let's consider another call to the
getNumber()
method as a part of an expression, as follows:
int a = 10;
int b = 19;
int c = getNumber(a, b) + a;
/* What is value of c at this point? */
It is little trickier to guess the value of
c
in the above snippet of code. You will need to consider the side effect
of the
getNumber()
method call on the actual parameters. The
getNumber()
method will return
8
, and it will also
modify the value of
a
and
b
to
3
and
5
, respectively. A value of
11
(
8 + 3
) will be assigned to
c
. Consider the following
statement in which you have changed the order of the operands for the addition operator:
int a = 10;
int b = 19;
int d = a + getNumber(a, b);
/* What is value of d at this point? */
The value of
d
will be
18
(
10 + 8
). The local value of 10 will be used for
a
. You need to consider the side effects
on actual parameters by a method call if the parameters are passed by reference. You would have thought that
expressions
getNumber(a, b) + a
and
a + getNumber(a, b)
would give the same results. However, when the
parameters are passed by reference, the result may not be the same, as I have explained above.
The advantages of using pass by reference are as follows:
•
It is more efficient, compared to pass by value, as actual parameters values are not copied.
•
It lets you share more than one piece of values between the caller and the called method
environments.
The disadvantages of using pass by reference are as follows:
•
It is potentially dangerous if the modification made to the actual parameters inside the called
method is not taken into consideration by the caller.
•
The program logic is not simple to follow because of the side effects on the actual parameters
through formal parameters.