public class AutoBoxingAndUnBoxing
{
public static void main(String[] args)
{
Integer x = 127;
Integer y = 127;
System.out.println(x == y);//true
Integer a = 128;
Integer b = 128;
System.out.println(a == b);//false
System.out.println(a); // prints 128
}
}
How come x==y
is true and a==b
is false? If it is based on the value(Integer -128 To 127
) then 'a'
should print -128
right?
When comparing Integer
objects, the ==
operator might work only for numbers between [-128,127]. Look at the 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.
Since that values you're comparing are not in the mentioned range, the result will be evaluated to false
unless you use Integer#equals
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With