javalong-integerincrement

(Potentially odd) long increment behavior?


I'm a bit embarrassed in asking this question, but the result of the following code snippet has me stumped:

System.out.println("incrementResultResponses() has been invoked!");
final long oldValue = resultResponses;
final long newValue = resultResponses++;
System.out.println("Old value = " + oldValue);
System.out.println("New value = " + newValue);

That outputs the following:

incrementResultResponses() has been invoked!
Old value = 0
New value = 0

Why? Would concurrency have any influence upon the result here? By the way, resultResponses is a long.


Solution

  • The postfix ++ operator returns the old value (before incrementing). You want to use prefix ++:

    final long oldValue = resultResponses++;
    final long newValue = ++resultResponses;