Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different output for same code in Java

Tags:

java

wrapper

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"

like image 746
Akash Gupta Avatar asked Mar 23 '26 12:03

Akash Gupta


1 Answers

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.

like image 192
Narendra Pathai Avatar answered Mar 26 '26 03:03

Narendra Pathai