88

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);
William
  • 8,630
  • 23
  • 77
  • 110

10 Answers10

106

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);
Grodriguez
  • 21,501
  • 10
  • 63
  • 107
  • 4
    If you must use a non-primitive int, and you want mutability, you can try commons MutableInt http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/mutable/MutableInt.html – Joel Sep 28 '10 at 17:03
  • thanks, but for some reason it's still not incrementing. Maybe it's a bug in my code... – William Sep 28 '10 at 17:04
  • 2
    @William : As i know, it will be incremented only in method that increment it. – Stan Kurilin Sep 28 '10 at 17:08
  • 13
    Don't use Integer's constructor. – ColinD Sep 28 '10 at 17:14
  • @ColinD: I believe that spelling it out like this makes it easier to see what is actually going on. – Grodriguez Sep 28 '10 at 17:44
  • 2
    @Grodriguez: Perhaps, though even then I'd suggest `Integer.valueOf(int)`... I don't like the idea of using bad practices in answers at all, it can lead to people thinking they're ok to do. I also think it's useful for the OP to realize that he can use operations he'd use with an `int` with an `Integer` in the same manner. – ColinD Sep 28 '10 at 17:52
  • @ColinD: "can lead to people thinking they're ok to do so"? I'm sorry, but it **is** OK to use the constructor, even though `Integer.valueOf(int)` is better. The fact that there are better alternatives (where available -- please note that some people is still stuck on pre-1.5 environments for different reasons) does not mean that using the constructor is "bad practice". And I still believe that my answer was clearer the way I wrote it. – Grodriguez Sep 28 '10 at 21:14
52

As Grodriguez says, Integer objects are immutable. The problem here is that you're trying to increment the int value of the player ID rather than the ID itself. In Java 5+, you can just write playerID++.

As a side note, never ever call Integer's constructor. Take advantage of autoboxing by just assigning ints to Integers directly, like Integer foo = 5. This will use Integer.valueOf(int) transparently, which is superior to the constructor because it doesn't always have to create a new object.

ColinD
  • 108,630
  • 30
  • 201
  • 202
23

Java 7 and 8. Increment DOES change the reference, so it references to another Integer object. Look:

@Test
public void incInteger()
{
    Integer i = 5;
    Integer iOrig = i;
    ++i; // Same as i = i + 1;
    Assert.assertEquals(6, i.intValue());
    Assert.assertNotEquals(iOrig, i);
}

Integer by itself is still immutable.

clemep
  • 124
  • 11
vitvlkv
  • 782
  • 7
  • 13
  • 1
    This is IMHO the best answer as it demonstrates the `++i` function (on variable `i`; note that you could have wrote `i++` as well) and the `Integer` class immutability (on variable `iOrig`). Most other answers demonstrate only one of the two notions. – Julien Kronegg Apr 01 '18 at 12:48
22

AtomicInteger

Maybe this is of some worth also: there is a Java class called AtomicInteger.

This class has some useful methods like addAndGet(int delta) or incrementAndGet() (and their counterparts) which allow you to increment/decrement the value of the same instance. Though the class is designed to be used in the context of concurrency, it's also quite useful in other scenarios and probably fits your need.

final AtomicInteger count = new AtomicInteger( 0 ) ;
…
count.incrementAndGet();  // Ignoring the return value. 
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Software Craftsman
  • 2,999
  • 2
  • 31
  • 47
8

Integer objects are immutable. You can't change the value of the integer held by the object itself, but you can just create a new Integer object to hold the result:

Integer start = new Integer(5);
Integer end = start + 5; // end == 10;
RHSeeger
  • 16,034
  • 7
  • 51
  • 41
6

For Java 7, increment operator '++' works on Integers. Below is a tested example

    Integer i = new Integer( 12 );
    System.out.println(i); //12
    i = i++;
    System.out.println(i); //13
samsamara
  • 4,630
  • 7
  • 36
  • 66
  • 4
    But be aware that other references to `i = new Integer(12)` will still refer to `12`, not `13`... easy to get tripped up on this one – vikingsteve Jan 15 '16 at 10:19
  • 1
    yeah thats why you have to reassign the value to the integer object: i = i++ – samsamara Jan 15 '16 at 12:14
  • 2
    `i = i++` is not the same as `i++`. Technically, the `++` doesn't really work on integers I'd say as you can't use it by itself without assigning the result to something. – Simon Forsberg May 14 '17 at 12:31
  • 2
    you don't have to reassign! look: Integer foo = 5; Integer bar = foo; foo++; System.out.println("foo: " + foo + " bar: " + bar); outputs: foo: 6 bar: 5 – clemep Feb 12 '18 at 20:07
5

Maybe you can try:

final AtomicInteger i = new AtomicInteger(0);
i.set(1);
i.get();
fantouch
  • 1,159
  • 14
  • 12
3

You can use IntHolder as mutable alternative to Integer. But does it worth?

Stan Kurilin
  • 15,614
  • 21
  • 81
  • 132
3

All the primitive wrapper objects are immutable.

I'm maybe late to the question but I want to add and clarify that when you do playerID++, what really happens is something like this:

playerID = Integer.valueOf( playerID.intValue() + 1);

Integer.valueOf(int) will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

Hamza Belmellouki
  • 2,516
  • 1
  • 18
  • 39
  • 1
    playerID = Integer.valueOf(playerID.intValue() + 1); A new Integer object is *not* always created. The autoboxing spec: https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7 If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2. Since Java 7, https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.15.1 also applies to the ++ operator – gary Nov 14 '19 at 16:51
  • Got it, answer edited. Incrementing the Integer object `playerID++` results in something like `playerID = Integer.valueOf( playerID.intValue() + 1)` and according to the method's docs: This method will always cache values in the range -128 to 127, inclusive. – Hamza Belmellouki Nov 14 '19 at 22:44
0

After Java 8, we can use as below

import java.lang.Math;
Math.incrementExact(playerID);
//it increment the integer value to + 1. It is also available for long
Harisudha
  • 527
  • 5
  • 5