2. Expressive Puzzlers

The puzzles in this chapter are simple. They involve only expression evaluation. But remember, just because they’re simple doesn’t make them easy.

Puzzle 1: Oddity

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;}

Solution 1: Oddity

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 ...

Get Java™ Puzzlers: Traps, Pitfalls, and Corner Cases now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.