Java Reference
In-Depth Information
Table 6-4.
Description of Memory States for Actual and Formal Parameters When the increment() Method is Called
and the Parameter is Passed by Value
Point of Execution
Memory State of Actual Parameter id
Memory State of Formal Parameter num
#1
The
id
variable exists in memory
and its value is 57.
The
num
variable does not exist at this point.
#2
The
id
variable exists in memory
and its value is 57.
The formal parameter,
num
, has been created in
memory. The value of the actual parameter
id
has
been copied to the address associated with the
num
variable. At this point,
num
holds the value of 57.
#3
The
id
variable exists in memory and
its value is 57.
At this point,
num
holds value of 59.
#4
The
id
variable exists in memory and
its value is 57.
The formal parameter,
num
, does not exist in memory
at this point because the method call is over.
All local variables, including formal parameters, are discarded when a method invocation is over. You can
observe that incrementing the value of the formal parameter inside the
increment()
method was practically useless
because it can never be communicated back to the caller environment. If you want to send back one value to the
caller environment, you can use a
return
statement in the method body to do that. The following is the code for the
smartIncrement()
method, which returns the incremented value to the caller:
// Assume that num is passed by value
int smartIncrement(int num) {
num = num + 2;
return num;
}
You will need to use the following snippet of code to store the incremented value that is returned from the
method in the
id
variable:
int id = 57;
id = smartIncrement(id); // Store the returned value in id
/* At this point id has a value of 59 */
Note that pass by value lets you pass multiple values from the caller environment to the method using multiple
parameters. However, it lets you send back only one value from the method. If you just consider the parameters in a
method call, pass by value is a one-way communication. It lets you pass information from the caller to the method
using parameters. However, it does not let you pass back information to the caller through the parameters. Sometimes
you may want to send multiple values from a method to the caller's environment through the parameters. In those
cases, you need to consider different ways to pass parameters to the method. The pass by value mechanism is of no
help in such situations.
A method that is used to swap two values does not work when the parameters are passed by values. Consider the
following code for a classical
swap()
method:
// Assume that x and y are passed by value
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}