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