Integer Wrapper equality test - Java

public class WrapperTest {

    public static void main(String[] args) {

     Integer i = 100;
     Integer j = 100;

     if(i == j)
      System.out.println("same");
     else
      System.out.println("not same");
    }

   }
The above code gives the output of "same" when run, however if we change the value of i and j to 1000 the output changes to "not same". 

Ans: In Java, Integers between -128 and 127 (inclusive) are generally represented by the same Integer object instance. This is handled by the use of a inner class called IntegerCache (contained inside the Integer class, and used e.g. when Integer.valueOf() is called, or during autoboxing):
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);
    }
}

Source: Stackoverflow

Comments

Popular posts from this blog

EJB - Stateful vs Stateless

Mirror binay tree - Java