Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why reference variables refer to different values in this example?

Tags:

java

public class AAA {
    public static void main(String[] args) {
        Integer bbb, aaa = new Integer(5);
        System.out.print(aaa);
        bbb = aaa;
        System.out.print(bbb);
        aaa = 4;  
        System.out.print(aaa);
        System.out.print(bbb);
    }
}

Why as a result I see: 5545 instead of 5544?

*java version "1.7.0_10"

Thank to all, I understood my mistake.

like image 579
Idel Pivnitskiy Avatar asked May 09 '26 16:05

Idel Pivnitskiy


1 Answers

public class AAA {
    public static void main(String[] args) {
        Integer bbb, aaa = new Integer(5);
        System.out.print(aaa);
        bbb = aaa;

The above line assigns bbb and aaa to point to the same object.

        System.out.print(bbb);
        aaa = 4;  

Now aaa points to a new object (which is created invisibly by autoboxing). This does not change the value of the original object which bbb still points to. Note that Integer is immutable. This means it is impossible to change the value of an Integer object. You can only a create new Integer object with a different value.

        System.out.print(aaa);
        System.out.print(bbb);
    }
}
like image 135
Code-Apprentice Avatar answered May 12 '26 08:05

Code-Apprentice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!