I remember reading a book named:
that described odd behavior in Java code. Stuff that look completely innocent but in actuality perform something completely different than the obvious. One example was:
(EDIT: This post is NOT a discussion on this particular example. This was the first example on the book I mentioned. I am asking for other oddities you might have encountered.)
Can this code be used to identify if a number is odd or not?
public static boolean isOdd(int i) {
return i % 2 == 1;
}
And the answer is of course NO. If you plug a negative number into it you get the wrong answer when the number is odd. The correct answer was:
public static boolean isOdd(int i) {
return i % 2 != 0;
}
Now my question is what are the weirdest, most counter intuitive piece of Java code you came across? (I know it's not really a question, maybe I should post this as a community wiki, please advice on that as well)