What do you think the output of this little Java program would be?
public static void main(String[] args) {
if (stuff() | stuff())
System.out.println("Goodbye");
}
static boolean stuff() {
System.out.println("Hello");
return true;
}
You may have expected it to print Hello and Goodbye because the true return value of stuff would force lazy evaluation of the conditional to return true.
However, if you ran the program you would see that Hello is printed twice, followed by Goodbye. The reason for this is because we used the bitwise OR ‘|’ not the logical OR ‘||’ and the bitwise OR always evaluates both sides of its parameters.
Inspired in part by Puzzle 42 of Java Puzzlers and also from a pretty horrible bug I found a while back.
Kezzer wrote:
November 20th, 2007 at 3:42 pm