O'Reilly logo

Java™ Puzzlers: Traps, Pitfalls, and Corner Cases by Neal Gafter, Joshua Bloch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required