(Potentially odd) behavior over a long increment?

I am a little awkward to ask this question, but the result of the following code fragment puzzled me:

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); 

This outputs the following:

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

Why? Can concurrency affect the result here? By the way, resultResponses is long .

+4
source share
4 answers

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

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

Since the increment increases the value after , it is assigned ( Post-Increment ). This is what resultResponses++ should do.
If you want resultResponses to be 1, you need to use Pre-Increment , which is ++resultResponses

+3
source

If you want to increase the value of oldValue to the destination, you will need to put ++ in front of the variable:

 final long newValue = ++resultResponses; 

This means that the increment occurs before the statement is executed, and not after.

+2
source

Consult this to find out how postfix and prefix . As mentioned in the answers above, you can use this:

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

Or, to make it more attractive, you can also use:

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

which also leads to the same conclusion.

0
source

Source: https://habr.com/ru/post/1395015/


All Articles