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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.