June 2005
Beginner to intermediate
312 pages
6h 24m
English
The puzzles in this chapter are simple. They involve only expression evaluation. But remember, just because they’re simple doesn’t make them easy.
The following method purports to determine whether its sole argument is an odd number. Does the method work?
public static boolean isOdd(int i) { return i % 2 == 1;}
An odd number can be defined as an integer that is divisible by 2 with a remainder of 1. The expression i % 2 computes the remainder when i is divided by 2, so it would seem that this program ought to work. Unfortunately, it doesn’t; it returns the wrong answer one quarter of the time.
Why one quarter? Because half of all int values are negative, and the isOdd method ...