Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing and Decrementing changing object value

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.

like image 636
Sathesh S Avatar asked Jul 08 '13 12:07

Sathesh S


3 Answers

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.

like image 87
Uwe Plonus Avatar answered Oct 14 '22 07:10

Uwe Plonus


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.

like image 38
Marko Topolnik Avatar answered Oct 14 '22 06:10

Marko Topolnik


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.

like image 2
Buhake Sindi Avatar answered Oct 14 '22 06:10

Buhake Sindi