Java Reference
In-Depth Information
Pass By Reference Value
The mechanism of passing parameters to a method using a pass by reference value is different from that of pass by
reference. However, both mechanisms have the same effects. In the pass by reference value, the reference of the actual
parameter is copied to the formal parameter. The formal parameter uses a dereferencing mechanism to access the
actual parameter's value. The modification made by the formal parameters inside the method is immediately visible
to the actual parameters, as is the case in pass by reference. Figure 6-8 depicts the memory states for the actual and
formal parameters when the pass by reference value mechanism is used.
Actual Parameter
Name
Actual Parameter
Address
Actual Parameter
Value
Formal parameter uses
dereferencing to access the
value of actual parameter
Actual parameter's
reference is copied to
formal parameter's location
Formal
Parameter
Address
Formal Parameter
Name
Actual Parameter
Address
Figure 6-8. Memory states for actual and formal parameters when a method call is made using pass by reference value
mechanism
There is an important difference between pass by reference and pass by reference values. In a pass by reference
value, the reference of the actual parameter is copied to the formal parameter as part of the method call. However,
you can change the formal parameter to refer to a different location in memory inside the method, which will not
make the actual parameter refer to the new location in memory. Once you change the reference stored in the formal
parameter, any changes made to the value stored at the new location will not change the value of the actual parameter.
The discussions and examples referring to the side effects and memory states for pass by reference also apply
to the pass by reference value mechanism. Most of the programming languages simulate the pass by reference
mechanism using pass by reference value.
Pass by Constant Reference Value
Pass by constant reference value is essentially the same as pass by reference value with one difference. The formal
parameter is treated as a constant inside the method body. That is, the formal parameter holds the copy of the
reference held by the actual parameter throughout the execution of the method. The formal parameter cannot be
modified inside the method's body to hold reference of data other than what the actual parameter is referencing.
 
 
Search WWH ::




Custom Search