1

Possible Duplicate:
Weird Java Boxing

public class example {
    public static void main(String[] args) {

        Integer a=127,b=127;
        if(a==b)
            System.out.println("Equal");
        else
            System.out.println("Not Equal");
        Integer c=128,d=128;
        if(c==d)
            System.out.println("Equal");
        else
            System.out.println("Not Equal");
    }

}

Output:

Equal
Not Equal
Community
  • 1
  • 1
Omkar
  • 11
  • 1

3 Answers3

5

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.

Hence when you tried to compare 127 with 127 there was only one object made and it worked right but when you tried with 128 it came out of the range and it created two objects so you can't compare them using == operator.

For this purpose use .equals()(Comparing Object reference) method.Please refer this for more details .

Integer c=128,d=128;
if(c.equals(d))
        System.out.println("Equal");
    else
        System.out.println("Not Equal");
Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 57
  • 1
    The [language spec](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7) requires that autoboxed ints in the range -128 (not -127) through +127 be cached. An implementation is free to cache other values as well (in which case +128 might have printed "Equals" as well). – Ted Hopp Nov 20 '12 at 08:00
  • 1
    @TedHopp do you know why they must be cached? – John Dvorak Nov 20 '12 at 08:02
  • @JanDvorak - It's required by the Java Language Specification. From the [JLS §5.1.7](http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7): _"If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2."_ See the link for some rationale as to why it's done this way. – Ted Hopp Nov 20 '12 at 08:09
0

This happens because Integer numbers within range [-128, 127] are stored in a heap. Thus, as you compare object references and not object values and both Integer a = 127 and Integer b = 127 point to the same object in a heap your expression is evaluated to true.

When Integer values are out of that range, you get two different objects, so reference comparison returns false

svz
  • 4,516
  • 11
  • 40
  • 66
  • 1
    Technically, they are stored in a static array, not in a heap (data structure; they are stored on _the_ heap (memory region), though) – John Dvorak Nov 20 '12 at 08:04
0

From the source code of Integer.java

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);
}
}

/**
 * Returns a <tt>Integer</tt> instance representing the specified
 * <tt>int</tt> value.
 * If a new <tt>Integer</tt> instance is not required, this method
 * should generally be used in preference to the constructor
 * {@link #Integer(int)}, as this method is likely to yield
 * significantly better space and time performance by caching
 * frequently requested values.
 *
 * @param  i an <code>int</code> value.
 * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
 * @since  1.5
 */
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache 
    return IntegerCache.cache[i + offset];
}
    return new Integer(i);
}
Shashi
  • 12,487
  • 17
  • 65
  • 111