3

I know that i am comparing reference while i'm using == which is not a good idea but i did not understand why is this happening.

Integer a=100;
Integer b=100;
Integer c=500;
Integer d=500;
System.out.println(a == b); //true
System.out.println(a.equals(b)); //true
System.out.println(c == d); //false
System.out.println(c.equals(d)); //true
Hiren
  • 1,427
  • 1
  • 18
  • 35
  • yeah it's duplicate!! i got perfect answer form here http://stackoverflow.com/questions/10002037/comparing-integer-values-in-java-strange-behavior. Thank you all. – Hiren Jun 15 '15 at 09:00

3 Answers3

15

The Java Language Specification says that the wrapper objects for at least -128 to 127 are cached and reused by Integer.valueOf(), which is implicitly used by the autoboxing.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
1

Integers between -128 and 127 are cached (Integers of the same value reference the same Object). Comparing your a and b references returns true, because they are the same Object. Your c and d are not in that range, so their reference comparison returns false.

dly
  • 1,080
  • 1
  • 17
  • 23
0

Integer values between -128 to 127 are being cached.

See the below Source code:

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

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);
}
  • a == b returns true means a and b references the same object. c == d returns false means c and d are not the same objects (even if their intValue are the same) – Max Jun 15 '15 at 08:22
  • Yes absolutely correct Mastov.... Initially i got confused too... Please delete irrelevant comments regarding to this post. Thanks you all – Anil Reddy Yarragonda Jun 15 '15 at 09:30
  • 1
    Just for closing this thread (And I was highlighting a little bit hard), is something very important from [choosen response in duplicate question](http://stackoverflow.com/questions/10002037/comparing-integer-values-in-java-strange-behavior) : **Moral: don't compare Integer references when you're interested in the underlying int values. Use .equals() or get the int values first.** – Max Jun 15 '15 at 11:15
  • Yes, but that was clear to everyone, it's even stated in the question! – mastov Jun 15 '15 at 12:10