Integer class in Java

I cannot figure out why the result is different.
The output is the same, only in the range from -128 to 127.

public class Check {
    public static void main(String[ ] args) {
        Integer i1=122;
        Integer i2=122;

        if(i1==i2)
            System.out.println("Both are same");
        if(i1.equals(i2))
            System.out.println("Both are meaningful same");
    }
}

      

Conclusion:
  Both are the same
  Both are significant the same

public class Check {
    public static void main(String[] args) {
        Integer i1=1000;
        Integer i2=1000;

        if(i1==i2)
            System.out.println("Both are same");
        if(i1.equals(i2))
            System.out.println("Both are meaningful same");
    }
}

      

Conclusion: Both are significant the same

+3


source to share


1 answer


You are faced with a caveat in Java where autoboxing for "small" values ​​has a slightly different rule than autoboxing. ("Small" in this case means a number in the range 127 to -128, as in signed byte

in C.) From JLS 5.1.7 Boxing Conversion :

If the value of p in a box is true, false, byte, a char in the range \ u0000 to \ u007f or an int or short number between -128 and 127, then let r1 and r2 be the result of any two box conversions on the page. It always happens that r1 == r2.



(My emphasis.)

In the second example (where i1=i2=1000

), the comparison if(i1==i2)

results in false

because the value of both objects is greater than 127. In this case, it ==

is a reference comparison, i.e. if the objects are actually the same object.

+4


source







All Articles