Can anyone tell me the reason for the change in output.
public class Demo {
public void demo()
{
Integer y = 567;
Integer x = y;
System.out.println(x + " " + y);
System.out.println(y == x);
y++;
System.out.println(x + " " + y);
System.out.println(y == x);
y--;
System.out.println(x + " " + y);
System.out.println(y == x);
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.demo();
}
}
OUTPUT:
567 567
true
567 568
false
567 567
False
Here why i'm getting the final false.
You are using Integer
which is an immutable object.
Basically your code is
y = new Integer(y.intValue() + 1);
and
y = new Integer(y.intValue() - 1);
Therefore you're creating two new Integer
objects that are not the same (==
) as the previous objects.
This behaviour is called autoboxing in Java.
Change your
Integer y = 567;
Integer x = y;
to
int y = 567;
int x = y;
and the suprprising behavior will be gone. My guess is that you have stumbled upon Java's implicit autoboxing of primitive values into wrapper objects, and are lead to believe that you are directly manipulating the numbers.
This is because the compiler does this internally:
y--
means:
int _y = y.intValue();
_y--;
y = Integer.valueOf(_y);
Therefore, y
is has a new Integer
instance. You are doing Object reference check (when using ==
) and not value equality check.
Use equals()
method to evaluate 2 values.
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