Page 257 - Introduction to Programming with Java: A Problem Solving Approach
P. 257

                6.11 Argument Passing 223 private double percentGrowthRate = 10; // % daily weight gain
public void grow(int days)
   }
// end class Mouse3
{
}
// end grow
this.age += days;
while (days > 0)
{
this.weight +=
.01 * this.percentGrowthRate * this.weight;
days--;
  }
Within a method, parameters are treated like local variables. The only difference is that a local vari- able is initialized inside the method, whereas a parameter is initialized by an argument in the method call. As you can see in the above loop body, the days parameter decrements down to zero. What happens to the days variable in the main method in Mouse3Driver? Because the two days variables are distinct, the days variable in the main method does not change with the days parameter in the grow method. So when Mouse3Driver prints its version of days, it prints the unchanged value of 365 like this:
# of days aged = 365.
Pass-By-Value
Apago PDF Enhancer
We say that Java uses pass-by-value for its argument-passing scheme. As illustrated by Figure 6.15, pass-by- value means that the JVM passes a copy of the argument’s value (not the argument itself) to the parameter. Changing the copy does not change the original.
In Mouse3Driver and Mouse3, notice that the calling method’s argument is called days and the grow method’s parameter is called days also. Is the parameter the same variable as the argument? No! They are separate variables separately encapsulated in separate blocks of code. Because these two variables are in separate blocks of code, there is no conflict, and it’s OK to give them the same name. Using the same name is natural because these two variables describe the same kind of thing. When names are in different blocks, you don’t have to worry about whether they are the same or not. That’s the beauty of encapsulation. Big programs would be horrible nightmares if you were prohibited from using the same name in different blocks of code.
Same Name Versus Different Names for Argument-Parameter Pairs
Most of the time, you’ll want to use the same name for an argument/parameter pair. But be aware that using different names is legal and fairly common. When it’s more natural and reasonable to use different names for an argument/parameter pair, then use different names. The only requirement is that the argument’s type must match the parameter’s type. For example, in the Mouse3 program, if num is an int variable, then the following method call successfully passes num’s value to the days int parameter:
minnnie.grow(num);
The JVM assigns the passed-in value to the days parameter.
 The days parameter decrements down to 0.










































































   255   256   257   258   259