How do I increment a Integer's value in Java? I know I can get the value with intValue, and I can set it with new Integer(int i).
playerID.intValue()++;
does not seem to work.
Note: PlayerID is a Integer that has been created with:
Integer playerID = new Integer(1);
Integer objects are immutable, so you cannot modify the value once they have been created.
If we use the "++" operator as a prefix like ++varOne; , the value of varOne is incremented by one before the value of varOne is returned. If we use ++ operator as postfix like varOne++; , the original value of varOne is returned before varOne is incremented by one.
By a++ , a new instance of Integer is created, and the value of it comes from adding a 1 to the original Integer object which both a and b are pointing to, and then a is re-assigned to this new object.
Integer
objects are immutable, so you cannot modify the value once they have been created. You will need to create a new Integer
and replace the existing one.
playerID = new Integer(playerID.intValue() + 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With