Java Reference
In-Depth Information
The following statement calls
doubleNumber
again, this time passing it the value
of
number
. This is an odd situation because the parameter has the same name as the
variable in
main
, but Java doesn't care. It always creates a new local variable for the
doubleNumber
method:
method
main
method
doubleNumber
x
17
number 42
number
42
So, at this point there are two different variables called
number
, one in each
method. Now it's time to execute the statements of
doubleNumber
again. It first
reports the value of
number
(
42
), then doubles it:
method
main
method
doubleNumber
x
17
number 42
number
84
Again, notice that doubling
number
inside
doubleNumber
has no effect on the
original variable
number
in
main
. These are separate variables. The method then
reports the new value of
number
(
84
) and returns to
main
:
method
main
x
17
number 42
The program then reports the value of
number
and terminates. So, the overall output
of the program is as follows:
Initial value = 17
Final value = 34
x = 17
Initial value = 42
Final value = 84
number = 42
The local manipulations of the parameter do not change these variables outside the
method. The fact that variables are copied is an important aspect of parameters. On
the positive side, we know that the variables are protected from change because the
parameters are copies of the originals. On the negative side, it means that although
parameters will allow us to send values into a method, they will not allow us to get
values back out of a method.
Search WWH ::
Custom Search