Java Magazine, Sept/Oct 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 77 fix this What do the two tests actually amount to First lets consider i1 io This test compares an int primitive value with an Integer object thats explicitly created by wrapping the same int value In this case the behavior of the operator is to extract the primitive int value wrapped by the object form and perform a comparison of primitive values Because the values on both sides are 1 the comparison returns true Notice particularly that Java Language Specification section 15211 indicates that the primitive value of the wrapper is extracted rather than a new Integer object being created by boxing the primitive If the latter had happened the result would have been false Java allows any data type to be concatenated with a String using the operator In the second case ib1 ib2 two object references are being compared This means that the comparison will return true only if the two references ib1 and ib2 refer to the same object If they had been created using invocations of the new operator they would have been diferent but in the special case of boxing small integers such as these the underlying system actually shares the objects from a pool Because of this the two references actually do refer to the same object in memory not merely to two objects with the same semantic meaning or boxed value So again the test produces true Its perhaps worth taking a moment to expand on that observation about pooling of objects used for boxing The first observation is that Java guarantees for a specific range of numbers that if you have the following assignments the test a b will be true Integer a 3 Integer b 3 This is possible and safe because the wrapper objects are immutable Therefore its safe to share them because they can never be changed Its relevant and worth doing to reduce the use of memory and thereby to also reduce the load on the garbage collector The specification says
You must have JavaScript enabled to view digital editions.