2

I am new to java. I know somewhat about the wrapper classes and primitive datatypes, but what I have come across is surprising. On changing the values of the variables i and j from 1000 to 100, the output changes from false to true. I need to know the mechanism behind this.

class Demo{
    public static void main(String[] args){
        Integer i=1000,j=1000;
        if(i==j)
            System.out.println("true");
        else
            System.out.println("false");
    }
}

the above code gives me "false" while..

class Demo{
    public static void main(String[] args){
        Integer i=100,j=100;
        if(i==j)
            System.out.println("true");
        else
            System.out.println("false");
    }
}

the above code give me "true"

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
Akash Gupta
  • 308
  • 1
  • 3
  • 15

3 Answers3

11

Caching in Wrapper Classes

Integer has internal cache for values ranging from -128 to 127.

So for numbers within this range, the same instance of Integer is returned. == compares by instance, and so the same instance is used for 100.

Source JDK 1.6:

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

Caching in wrapper classes Java

Purpose of Caching

The purpose is mainly to save memory, which also leads to faster code due to better cache efficiency.

Use .equals when comparing value, not identity

If you are comparing two Integers, you should use i.equals(j) just like you would do to correctly compare the value of Strings. Also keep in mind that any operation which will unbox an Integer places an implicit call to Integer.intValue(), so remember to make these calls carefully, knowing when your Integer might be null.

Nicole
  • 32,841
  • 11
  • 75
  • 101
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
  • No problem, great answer, just thought I'd make that clear in case it wasn't obvious. – Nicole Sep 18 '13 at 08:23
  • I'd like to know who has choose this range of value (-128 to 127) and why ? Why not a higher range ? – soung Jan 05 '20 at 15:15
1

To compare the contents of objects (instead of their identity) use equals instead of ==. This will give consistent results.

Henry
  • 42,982
  • 7
  • 68
  • 84
0

Wrapper class Integer has internal cache for -127 to 127. So when you assign same values which are within this range same instance will be returned. For 1000 two different 'new'ed instances are returned giving false on == comparision.

If you use int instead of Integer, results will not be surprising. For consistent result with your approach, use equals() method instead of ==.

Vallabh Patade
  • 4,960
  • 6
  • 31
  • 40