Java Reference
In-Depth Information
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.
You might wonder why the language specification wasn't changed to make the equality operators
perform value comparisons when applied to boxed numeric types. The answer is simple:
compatibility. When a language is widely used, it is unacceptable to change the behavior of existing
programs in ways that violate existing specifications. The following program was always
guaranteed to print false , and so it must remain:
public class ReferenceComparison {
public static void main(String[] args) {
System.out.println(new Integer(0) == new Integer(0));
}
}
The equality operators do perform numerical comparison when only one of their two operands is of
a boxed numeric type and the other is of a primitive type. Because this was illegal prior to release
5.0, there are no compatibility problems. To make this concrete, the following program was illegal
in release 1.4 and prints TRue in release 5.0:
public class ValueComparison {
public static void main(String[] args) {
System.out.println(new Integer(0) == 0);
}
}
In summary, there is a fundamental difference in the way numerical comparison operators and
equality operators behave when both operands are of boxed numeric types: Numerical
comparison operators perform value comparisons, while equality operators perform reference
identity comparisons .
For language designers, life might have been simpler and more pleasant if the equality operators
 
 
Search WWH ::




Custom Search