Provide declarations for i and j that turn this loop into an infinite loop:
while (i <= j && j <= i && i != j) {
}
The <= operator is still antisymmetric on the set of primitive numeric values, but now it applies to operands of boxed numeric types as well. (The boxed numeric types are Byte, Character, Short, Integer, Long, Float, and Double.) The <= operator is not antisymmetric on operands of these types, because Java's equality operators (== and !=) perform reference identity comparison rather than value comparison when applied to object references.
To make this concrete, the following declarations give the expression (i <= j && j <= i && i != j) the value true, turning the loop into an infinite loop:
Integer i = new Integer(0);
Integer j = new Integer(0);
The first two subexpressions (i <= j and j <= i) perform unboxing conversions [JLS 5.1.8] 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.
No comments:
Post a Comment