public class WrapperTest { public static void main(String[] args) { Integer i = 100; Integer j = 100; if(i == j) System.out.println("same"); else System.out.println("not same"); } }
The above code gives the output of same
when run, however if we change the value of i
and j
to 1000 the output changes to not same
. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.
When a wrapper is compared with a primitive using ==, the wrapper is unwrapped. That's true! But which method is invoked/called depends on the type of the wrapper. If your wrapper is of type Integer, then indeed the intValue method will be called.
Comparing Integers Integer is a wrapper class of int, and it provides several methods and variables you can use in your code to work with integer variables. One of the methods is the compareTo() method. It is used to compare two integer values. It will return a -1, 0, or 1, depending on the result of the comparison.
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 != .
In Java, Integers between -128 and 127 (inclusive) are generally represented by the same Integer object instance. This is handled by the use of a inner class called IntegerCache (contained inside the Integer class, and used e.g. when Integer.valueOf() is called, or during autoboxing):
private static class IntegerCache { private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } }
See also: http://www.owasp.org/index.php/Java_gotchas
Basically Integers between -127 and 127 are 'cached' in such a way that when you use those numbers you always refer to the same number in memory, which is why your ==
works.
Any Integer outside of that range are not cached, thus the references are not the same.
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