Thursday, August 18, 2005

That's Odd?!?

For newbies and experts alike, a common pitfall of a java developer is the extra validation for negative and positive primitive numeric values. Most of us just happily pound away on the keyboard, oblivious that there are indeed negative numbers in the java world. Check why this method won't work:


public boolean checkIfOdd(int num) {
return num % 2 == 1;
}


Again, contrary to the instinctive yes answer, this won't work half of the time. Why? Because half of the integers are negative, half are not. This method will falsely identify negative numbers as an even number.

The info of this oddity is courtesy of the Java Puzzlers book.

richard@work

1 comment:

Anonymous said...

public boolean checkIfOdd(int num) {
return num & 0x1 != 0;
}