Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer's specific (Java Core) [duplicate]

Tags:

java

i've got this question on interview:

public Integer v1 = 127;
public Integer v2 = 127;
public Integer v3 = 513;
public Integer v4 = 513;

public void operatorEquals(){
    if (v1==v2)
        System.out.println("v1 == v2");
    else throw new RuntimeException("v1 != v2");
    if (v3==v4)
        System.out.println("v3 == v4");
    else throw new RuntimeException("v3 != v4");
}

**Result**: java.lang.RuntimeException: **v3 != v4**

Can you explain: why? I have no suggestions.

like image 472
user2171669 Avatar asked Oct 02 '13 18:10

user2171669


2 Answers

Java Integer objects are cached until 127, but not above.

The effect of this is very similar to how the String interning works, so all Integer objects with values in the range [-128;127] are the same instances too -- returning true with referential equality check too, (e.g. ==), not only using .equals().

EDIT from Arnaud Denoyelle

From Integer.java :

public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
like image 155
ppeterka Avatar answered Sep 21 '22 02:09

ppeterka


This is the defined behaviour for Java when Autoboxing. Check the relevant Java Language Specification section. Read the discussion section there also. The following paragraph is taken from the specification:

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.

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.

This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

For ints, those between -128 and 127 (inclusive) autoboxed Integer objects will return true for the check ==. It is said that these integers are cached and in a constant pool. But if you just do new Integer(int) the objects created will always be different.

like image 35
Sage Avatar answered Sep 19 '22 02:09

Sage