-2
Integer v1_1 = 127;
Integer v1_2 = 127;

Integer v2_1 = 128;
Integer v2_2 = 128;

System.out.println(v1_1 == v1_2);//true
System.out.println(v2_1 == v2_2);//false

Why second expression is false?

I couldn't figure it out how the value affect the comparison result.

Cengiz Dogan
  • 149
  • 1
  • 13
  • 1
    Never use `==` to compare objects. (The way Java does "boxing" is very confusing to the novice -- worse than not having it at all, IMO.) – Hot Licks Jan 13 '15 at 12:31
  • I know i never use it that way but i just wonder how could it be, now i understand why. – Cengiz Dogan Jan 13 '15 at 12:33

2 Answers2

8

Because the Integer type interns the values (by the static class IntegerCache) from -128 to 127.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
3

Because Integer class uses IntegerCache internally which caches object from -128 to 127. For e.g. When you call valueOf , the Integer class checks whether value is in the cache or not like this

   public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

If the value exists in cache then you get the same object. Thats why

System.out.println(v1_1 == v1_2);//returns true
sol4me
  • 15,233
  • 5
  • 34
  • 34