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

                public void grow(int days)
{
}
// end grow
int endAge = this.age + days;
while (this.age < endAge)
{
if (this.age >= 100)
{
In this variation of the grow method, we cut off the aging process at 100 days—after “adolescence”—by checking age inside the loop and returning when age is greater than or equal to 100. Notice the empty return statement. Since nothing is returned, the method heading must specify void for its return type.
It would be illegal to have an empty return statement and a non-empty return statement in the same method. Why? Empty and non-empty return statements have different return types (void for an empty return statement and some other type for a non-empty return statement). There is no way to
specify a type in the heading that simultaneously matches two different return types.
}
// end grow
}
endAge = 100;
while (this.age < endAge)
{
Apago PDF Enhancer
The empty return statement is a helpful statement in that it provides an easy way to exit quickly from a method. However, it does not provide unique functionality. Code that uses an empty return statement can always be replaced by code that is devoid of return statements. For example, here’s a return-less version of the previous grow method:
public void grow(int days)
{
int endAge = this.age + days;
if (endAge > 100)
{
this.weight +=
.01 * this.percentGrowthRate * this.weight;
this.age++;
} // end while
return Statement Within a Loop
Programmers in industry often are asked to maintain (fix and improve) other people’s code. In doing that, they often find themselves having to examine the loops and, more specifically, the loop termination
6.10 The return Statement 221
   }
this.age++;
// end while
}
return;
empty return statement
this.weight +=
.01 * this.percentGrowthRate * this.weight;



























































   253   254   255   256   257