Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer comparison in Java [duplicate]

Integer comparison in Java is tricky, in that int and Integer behave differently. I get that part.

But, as this example program shows, (Integer)400 (line #4) behaves differently than (Integer)5 (line #3). Why is this??

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.format("1. 5              == 5            : %b\n", 5 == 5);
        System.out.format("2. (int)5         == (int)5       : %b\n", (int)5 == (int)5);
        System.out.format("3. (Integer)5     == (Integer)5   : %b\n", (Integer)5 == (Integer)5);
        System.out.format("4. (Integer)400   == (Integer)400 : %b\n", (Integer)400 == (Integer)400);
        System.out.format("5. new Integer(5) == (Integer)5   : %b\n", new Integer(5) == (Integer)5);
    }
}

Result

1. 5              == 5            : true  // Expected
2. (int)5         == (int)5       : true  // Expected
3. (Integer)5     == (Integer)5   : true  // Expected
4. (Integer)400   == (Integer)400 : false // WHAT?
5. new Integer(5) == (Integer)5   : false // Odd, but expected
like image 881
abelenky Avatar asked Apr 08 '15 12:04

abelenky


2 Answers

Because in autoboxing a literal to Integer , are evaluated as following:

(Integer)400 --- Integer.valueOf(400)

valueOf is implemented such that certain numbers are "pooled", and it returns the same instance for values smaller than 128.

And since (Integer)5 is less than 128, it would be pooled and (Integer)400won't be pooled.

Therefore:

3. (Integer)5     == (Integer)5   : true  // Expected -- since 5 is pooled (i.e same reference)

and

4. Integer(400)   == (Integer)400 : false // WHAT? -- since 400 is not pooled (i.e different reference)
like image 91
Darshan Lila Avatar answered Sep 18 '22 18:09

Darshan Lila


Here is a quote from JLS:

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.

In short Integer uses pool, so for numbers from -128 to 127 you will get always the same object after boxing, and for example new Integer(120) == new Integer(120) will evaluate to true, but new Integer(130) == new Integer(130) will evaluate to false.

like image 32
nikis Avatar answered Sep 18 '22 18:09

nikis