Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Integer class does not behave as reference type

Integer doesn’t behave as a Reference Type. For example code below produces unexpected result


    class Playground {
            public static void main(String[ ] args) {
                Integer i = 10;
                Integer num = i;
                i--;
                System.out.println("i = " + i);
                System.out.println("num = " + num);
            }
    }

OUTPUT:

i = 9
num = 10

I have expected "num" to be 9 as well cause Integer "num" references Integer "i". The substractaction happens here from the same object num is referencing, but looks like "-" operator is overriding some behaviour and creates an new Integer object. What exactly is happening here? And what other classes behave like that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Integer objects are immutable.

After Integer num = i; the local variable num references the same Integer object as i – specifically an Integer object that contains the value 10.

But when you write i--; then i can no longer reference the same Integer object as num – the local variable i gets assigned with a reference to an Integer object that contains the value 9.

Since num was not assigned to it still references the Integer object with the value 10.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading