Page 256 - Introduction to Programming with Java: A Problem Solving Approach
P. 256
222 Chapter 6 Object-Oriented Programming
conditions in the program they’re working on. Therefore, it’s important that loop termination conditions are clear. Normally, loop termination conditions appear in the standard loop-condition section. For while loops, that’s the header, for for loops, that’s the header’s second component, and for do loops that’s the closing. However, a return statement inside a loop results in a loop termination condition that’s not in a standard location. For example, in the first grow method on the previous page the return statement is inside an if statement and the loop termination condition is consequently “hidden” in the if statement’s condition.
In the interest of maintainability, you should use restraint when considering the use of a return state- ment inside a loop. Based on the context, if inserting return statements inside a loop improves clarity, then feel free to insert. However, if it simply makes the coding chores easier and it does not add clarity, then don’t insert. So which grow implementation is better—the empty return version or the return-less ver- sion? In general, we prefer the return-less version for maintainability reasons. However, because the code in both of our adolescent grow methods is so simple, it doesn’t make much difference here.
6.11 Argument Passing
In the previous section you saw that when a method finishes, the JVM effectively assigns the return value to the method call. This section describes a similar transfer in the other direction. When a method is called, the JVM effectively assigns the value of each argument in the calling statement to the corresponding param- eter in the called method.
Example
Apago PDF Enhancer
Let’s examine argument passing by looking at an example—another version of our Mouse program called Mouse3. Here is the code for this new version’s driver:
public class Mouse3Driver
{
public static void main(String[] args)
{
}
// end class Mouse3Driver
}
Mouse3 minnie = new Mouse3();
int days = 365;
minnie.grow(days);
System.out.println("# of days aged = " + days);
// end main
The Mouse3Driver class calls the grow method with an argument called days, whose value hap- pens to be 365. Then it assigns this value (365) to the parameter called days in the grow method. The fol- lowing code shows what happens to the days parameter within the grow method:
public class Mouse3
{
private int age = 0;
// age in days
private double weight = 1.0;
// weight in grams
The JVM makes a copy of days’s
value and passes it to the grow method.