0
Comparison of boxed Integers
Within a challenge I came across the question, whether two Integers of value 100 would compare to "true" or "false" using the "==" operator. I answered "true", while obviously "false" was expected. As to my knowledge, boxed Integers within range -128 to 127 are implemented as Singletons in Java, so the use of "==" should yield "true" within this range, as both Integers reference the same object. Am I right or wrong here?
1 ответ
0
I have just found out that the result of the comparison depends on how the Integer objects were obtained.
If an Integer was instantiated using the "new" operator, a new Integer object will be created. Thus comparing two Integer objects using "==" will yield "false" if at least one of the Integers was instantiated with the "new" operator.
Integer a = new Integer(100);
Integer b = new Integer(100);
a==b yields "false"
Only if both Integers were obtained by assignment of an int-value ranging from -128 to 127, the runtime will use a previously instantiated boxed Integer, probably to spare the time required to instantiate a new boxed value.
Consequently, if
Integer a = 100;
Integer b = 100;
a==b yields "true".
Just a piece of trivia, however. Comparing Integer values using the "==" operator is not recommendable anyway. ;-)