Sunday, August 07, 2005

Java puzzle

What should be the declarations for i and j to make this loop infinite?
while (i <= j && j <= i && i != j) {
}
Anyone who knows basic maths would say this is impossible. Even the Java[TM] programmers who haven't tried JSE release 5.0 would say the same. But it is no longer true in JSE release 5.0. Let me give you the answer taken from 2005 JavaOne Conference Code Talks.
Integer i = new Integer(0);
Integer j = new Integer(0);
The first two subexpressions (i <= j and j <= i) perform unboxing conversions on i and j and compare the resulting int values numerically. Both i and j represent 0, so both of these subexpressions evaluate to true. The third subexpression (i != j) performs an identity comparison on the object references i and j. The two variables refer to distinct objects, as each was initialized to a new Integer instance. Therefore, the third subexpression also evaluates to true, and the loop spins forever!!

Link

0 Comments:

Post a Comment

<< Home