Java is the future !: What's up with integers not being equal to one another? The following code prints "true, true, false, true". Shouldn't it be "true, true, true, true"?

Sunday, April 24, 2011

What's up with integers not being equal to one another? The following code prints "true, true, false, true". Shouldn't it be "true, true, true, true"?



The key to understanding this is that the JVM uses a process called "boxing" (or "auto-boxing") when converting an int (like 127) to an Integer object. This involves calling the Integer.valueOf(127) method. The JavaDoc:java.lang.Integer#valueOf(int) says: "Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values." What that means is that the valueOf() method has a cache of Integer objects, and if the primitive being boxed is in that range, the cached object is returned. It just so happens that 127 is in that range, but 128 is not. So i and j are the same object, while i1 and j1 are not.

Source: CodeRanch

No comments:

Post a Comment