So I was asked this question today.
Integer a = 3;
Integer b = 2;
Integer c = 5;
Integer d = a + b;
System.out.println(c == d);
What will this program print out? It returns true. I answered it will always print out false because of how I understood auto (and auto un) boxing. I was under the impression that assigning Integer a = 3 will create a new Integer(3) so that an == will evaluate the reference rather then the primitive value.
Can anyone explain this?
In Java, when primitive values are boxed into a wrapper object, certain values (any boolean, any byte, any char from 0 to 127, and any short or int between -128 and 127) are interned, and any two boxing conversions of one of these values are guaranteed to result in the same object.
A boxed type means that the values are allocated in a block on the heap and referenced through a pointer. This is good for uniformity in the implementation of the runtime (it makes it easier to have generic functions, etc), at the cost of an additional indirection.
Like in other languages, we can compare the values of primitives with the < , > , <= , and >= operator. The same problems of floating-point data types apply to them, so be aware. Also, boolean isn't comparable except for equality with == and != .
This compliant solution uses the equals() method to perform value comparisons of wrapped objects.
Boxed values between -128 to 127 are cached. Boxing uses Integer.valueOf
method, which uses the cache. Values outside the range are not cached and always created as a new instance. Since your values fall into the cached range, values are equal using == operator.
Quote from Java language specification:
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With