++ operator, why this behaviour ?

Check this snippet :

Integer i = 42;
Integer j = i; // copy reference
++j; // increment value
System.out.println("" + i + j); // print 4243
System.out.println(i == j); // print false

This code uses reference, then why both references don’t increase simultaneously, and why references are not equals ?
Remember that operator overloading doesn’t exist in Java. Thus here, ++ operator cannot act on j with j considered as a reference. Indeed increment operator can be applied only on primitive types, but here j is reference and this code compile and run fine.

In fact, when you increase a value with ++ operator on Integer, javac use boxing and unboxing.
Here, to use ++ operator on Integer, javac unbox the int value from reference, increase it, and rebox it into a new reference (the old will be lost and cleared by the garbage collector).
Because j is a different reference, equality fails, and values are different (only j has the new value).

For best understanding, check this code, it look like the real behavior of increment operator on Integer reference :

Integer i = 42;
Integer j = i;
int _j = j;
++_j;
j = Integer.valueOf(_j);
System.out.println("" + i + j);
System.out.println(i == j);

This version of the code is simplified, but if you compile the first snippet, and uncompile it (with jad), you’ll get :

Integer i = Integer.valueOf(42);
Integer j = i;
j = Integer.valueOf(j.intValue() + 1);

This behaviour is very rarely annoying, but it’s fun to know that.

Advertisements

One thought on “++ operator, why this behaviour ?

  1. Hello There. I found your weblog the use of msn. That is a really neatly written article.
    I will make sure to bookmark it and come back to
    learn more of your useful info. Thanks for the post.
    I’ll definitely comeback.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s