Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment a Integer's int value?

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); 
like image 908
William Avatar asked Sep 28 '10 16:09

William


People also ask

Can you increment an integer?

Integer objects are immutable, so you cannot modify the value once they have been created.

How do you increment a value in Java?

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.

What would happen if I will use ++ in an integer?

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.


1 Answers

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); 
like image 199
Grodriguez Avatar answered Sep 29 '22 05:09

Grodriguez