I was doing a review of some code and came across an instance of someone post-incrementing a member variable that was a wrapper class around Integer. I tried it myself and was genuinely surprised that it works.
Integer x = 0;
System.out.print(x++ + ", ");
System.out.print(x);
This prints out 0, 1
, not 0, 0
as I would have expected. I've looked through the language specification and can't find anything covering this. Can anyone explain to me why this works and if it's safe across multiple platforms? I would have thought that this would decompose into
Integer x = 0;
int temp1 = x.intValue();
int temp2 = temp1 + 1;
System.out.println(temp1);
temp1 = temp2;
System.out.println(x.intValue());
But apparently there's something in the specification that make it add x = temp1;
before the last line
++
operator applies only to (primitive) integer types. Behind the scenes,x
is unboxed, the++
is applied, and the result is then assigned back tox
(after a boxing conversion). TheInteger
class does not have a++
operator. In fact,Integer
objects are immutable. – Junie0, 0
? – Junie++
to change the value of the variable to which it is applied, and having wrapper classes should not conflict with that expectation. – Junieconst
seems flawed. You can't use++
with aconst int
in C++. So you should expect either to not be able to apply++
to a JavaInteger
at all, or for it to behave just like anint
, not aconst int
. (Java tries to makeInteger
behave as much likeint
as possible.) – Junie