Autoboxing Unboxing Operator (!=) and (==) difference [duplicate]
Asked Answered
T

5

10
public class T1 {    

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Integer i1 = 1000;
        Integer i2 = 1000;
        if(i1 != i2) System.out.println("different objects");
        if(i1.equals(i2)) System.out.println("meaningfully equal");    

    }

}

O/P for this is:

different objects
meaningfully equal

Where as

public class T2 {    

    public static void main(String[] args) {            

        Integer i3 = 10;
        Integer i4 = 10;
        if(i3!=i4)System.out.println("Crap dude!!");
        if(i3 == i4) System.out.println("same object");

        if(i3.equals(i4)) System.out.println("meaningfully equal");    
    }

}

Produces Following O/P:

same object
meaningfully equal

I didn't understand why in class T2 if(i3!=i4) didn't get triggered I'm refering SCJP 1.6 but not able to understand.
Please help me.

Turgot answered 26/12, 2013 at 12:12 Comment(3)
Note that you used "1000" in the first example and "10" in the second example.Cummerbund
Learn about cache range for integers in Java. Read Javadoc, source code, ... of Integer wrapper class.Heinrike
Ok.. thanks kenny and Rohit.Turgot
N
10

This is because 10 is in between the range [-128, 127]. For this range == works fine since the JVM caches the values and the comparison will be made on the same object.

Every time an Integer (object) is created with value in that range, the same object will be returned instead of creating the new object.

See the JLS for further information.

Network answered 26/12, 2013 at 12:13 Comment(1)
This can be wrong, since Integer.valueOf does caching, the constructor can't. The compiler internally compiles Integer i = 0; to Integer i = Integer.valueOf(0);, which is why this works in this case.Prefect
A
4

There is Integer pool for the numbers from -128 to 127 in java. JLS says

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.

Alchemize answered 26/12, 2013 at 12:13 Comment(0)
K
4

Small integers get interned, meaning that there's only one instance of Integer for the given value.

This doesn't happen for large integers, hence the difference in behaviour between your two tests.

Korea answered 26/12, 2013 at 12:14 Comment(1)
so if we are creating two objects of Integer within [-128 to 127] with same value then only one object with that value would be created and they both reference variables would be pointing to that object. Am i right?Turgot
C
2

Integer are cached between range -128 to 127. so Integer in between the range(containing boundary values) will return the same reference..

like

Integer i3 = 127;
Integer i4 = 127;
Integer i5 = 128;

 if(i3!=i4)System.out.println("Crap dude!!");   // same reference
 if(i3 == i4) System.out.println("same object"); 
 if(i3 != i5) System.out.println("different object");   

output..

same object
different object

As '==' compares reference and 'equals' compares content. for more detail You may go to Immutable Objects / Wrapper Class Caching

Canzonet answered 26/12, 2013 at 12:43 Comment(5)
I think output should be Crap dude!! different object.Turgot
You might have misspelled 1 (i4). Did you mean 127?Prefect
@SaurabhSharma, dude output is same as written above..Canzonet
@TarunChaudhary I tried it it gives Crap dude!! different object. And i agree this output because 127 and 1 both are different values so they can't be meaningfully equal.Turgot
oh now you edited that right :D previously it was 1.Turgot
H
2

anyway you can get double false with:

Integer n1 = -1000;
Integer n2 = -1000;

Integer p1 = 1000;
Integer p2 = 1000;

System.out.println(n1 == n2);
System.out.println(p1 != p2);

there is an option to set max size of this Integer pool

  /**
   * Cache to support the object identity semantics of autoboxing for values between
   * -128 and 127 (inclusive) as required by JLS.
   *
   * The cache is initialized on first usage.  The size of the cache
   * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
   * During VM initialization, java.lang.Integer.IntegerCache.high property
   * may be set and saved in the private system properties in the
   * sun.misc.VM class.
   */
Hollingshead answered 26/12, 2013 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.