Writing Methods
public class Pool
{
private int swimmers;
private int lanes;
public Pool(int s, int l)
{
swimmers = s;
lanes = l;
}
public void announce()
{
System.out.println("Pool open");
}
public int perLane()
{
return swimmers / lanes;
}
public boolean isCrowded()
{
return swimmers > lanes * 4;
}
}
Of the three methods in
Pool, announce returns nothing, and the other two each return a value.Using the value
For a pool built with
new Pool(18, 6), the call perLane() evaluates 18 / 6 and returns 3. The caller receives the 3, not the expression, and the call can be used anywhere an int can.Pool city = new Pool(18, 6);
city.announce();
int each = city.perLane();
boolean wait = city.isCrowded() || each > 4;
The call to
announce is written alone on its line, since there's no value to store or test. The other two calls are used as values. Since 18 isn't more than 6 times 4, isCrowded() returns false, and since 3 isn't more than 4, wait is false.Printing a value isn't returning it. A method that prints the number of swimmers per lane shows it on the screen, but the caller gets nothing to store or compare. The return type comes from what the caller needs: a value, or only the effect.
Return types
A comparison like
swimmers > lanes * 4 has a boolean value, so isCrowded is declared boolean. A method declared double can return an int value, which is converted on the way out: a method public double laneCount() that returns lanes gives 6.0. The reverse doesn't compile; a double value can't be returned from a method declared int.Where a method ends
A
return statement sends its value back and ends the method at once, even inside a loop. This method reports whether a group could join without going over 4 swimmers a lane.public boolean canFit(int group)
{
int room = 0;
for (int n = 1; n <= lanes; n++)
{
room = room + 4;
if (room >= swimmers + group)
{
return true;
}
}
return false;
}
For a group of 2, the pool needs room for 20. The room reaches 20 at the fifth lane, so the method returns
true there, and the sixth lane is never counted. For a group of 10, the pool would need 28, the room tops out at 24, the loop ends, and the method returns false.The final
return false; is required. A non-void method must return a value on every path through it. Without that line, the path where the loop finishes would reach the closing brace with nothing to return, and the method wouldn't compile. A statement placed directly after a return in the same block can never run, and the compiler rejects it as unreachable.