Javatm Puzzlers: Traps, Pitfalls, and Corner Cases
[Computer]

One of the books I've just finished reading is Javatm Puzzlers: Traps, Pitfalls, and Corner Cases by Joshua Bloch and Neal Gafter. The book is intended to people who already know Java pretty well, and challenges the reader to guess what a given Java program will do. These Java programs are almost always less than 20 lines long, and yet they almost always managed to surprise me. Of the 95 "puzzles" programs in the book, I only correctly predicted the output of 3 of them. Almost every puzzle is accompanied with an explanation of the behaviour, sometimes diving deep into the Java Language Specification.

For example, this method is supposed to determine whether a number is even or odd, but it doesn't work. Can you find the bug:

public static boolean isOdd(int i) { return i % 2 == 1; }

Or how about this program? What do you think it outputs?

public class Elementary { public static void main(String[] args) { System.out.println(12345 + 5432l); } }

Hint: If you think it prints out 66666 (as I did), you're wrong. The authors assert that if a program doesn't do what it looks like it's doing, that's a bug in the source code and should be fixed. Along with the solutions to each puzzle, the authors recommend common-knowledge good programming practices, and point out how if only these guidelines were followed, the demonstrated bug would never have resulted. "Never return from, or throw exceptions in a 'finally' block"; there are two puzzles in the book showing why. "Don't catch 'Error' or its subclasses"; there's a puzzle demonstrating why this is dangerous. "Prefer static member classes to inner classes"; 4 puzzles show why the latter probably aren't what you want in most situations.

If you are a good Java programmer and want to become a great one, I recommend this book.

 
E-mail this story to a friend.
1. przemek said:

Input:

public class T1

{

public static void main(String[] args)

{

for(int i=0;i<10;i++)

{

System.out.println("i="+i+" odd "+isOdd(i));

}

}

public static boolean isOdd(int i) { return i % 2 == 1;} }

and here is the output (jdk 1.4, win xp):

i=0 odd false

i=1 odd true

i=2 odd false

i=3 odd true

i=4 odd false

i=5 odd true

i=6 odd false

i=7 odd true

i=8 odd false

i=9 odd true

So where is the bug??

The second "12345 + 5432l" is a nice catch, but that is rather a problem of IDE/editor (you can also make a mistake with "0" and "O" for example)

Posted on Wed October 5th, 2005, 6:49 AM EST acknowledged
2. b0b0b0b said:
I felt so smart when I realized the bug in isOdd. I am so smart I am so smart
Posted on Wed October 5th, 2005, 12:18 PM EST acknowledged
3. Nebu Pookins said:

Here's the bug for this first one: It doesn't work for negative numbers; it claims -1 is an even number.

Posted on Sun October 9th, 2005, 6:57 PM EST acknowledged

You must be logged in to post comments.

Sites linking to this post: