Egor Khorozhansky
Egor Khorozhansky

Reputation: 3

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?

Upvotes: 0

Views: 376

Answers (1)

Thomas Kläger
Thomas Kläger

Reputation: 21435

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.

Upvotes: 5

Related Questions