Java Reference
In-Depth Information
Figure 6-6 depicts the memory state when a method is called using the pass by value mechanism. It is to be
emphasized that once the formal parameter gets its value, which is a copy of the actual parameter, the two parameters
have nothing to do with each other. The formal parameter is discarded at the end of the method call. However, the
actual parameter persists in memory after the method call ends. How long the actual parameter persists in memory
depends on the context of the actual parameter.
Actual Parameter
Name
Actual Parameter
Address
Actual Parameter
Value
Actual parameter
value is copied to
formal parameter
location
Formal
Parameter
Address
Formal Parameter
Name
Actual Parameter
Value
Figure 6-6. Memory states for actual and formal parameters when a method is called
Let's consider the following code for the increment() method, which accepts an int parameter and increments
it by 2 :
// Assume that num is passed by value
void increment(int num) {
/* #2 */
num = num + 2;
/* #3 */
}
Suppose you call the increment() method with the following snippet of code:
int id = 57;
/* #1 */
increment(id);
/* #4 */
Four points of executions in the code are labeled as #1, #2, #3, and #4. Table 6-4 describes the memory states for
the actual parameter and the formal parameter, before, after, and when the increment() method is invoked. Note that
the formal parameter num no longer exists in memory at #4.
 
 
Search WWH ::




Custom Search