Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(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.

like image 453
mre Avatar asked Feb 06 '12 13:02

mre


People also ask

Is ++ OK in JavaScript?

Crockford and Firebug have filled these holes in JavaScript education. ++ doesn't cause bugs. Using ++ in "tricky" ways can lead to bugs, especially if more than one person is maintaining the codebase, but that's not a problem with the operator, it's a problem with the programmer.

What is ++ i in Python?

Python does not have unary increment/decrement operator( ++/--). Instead to increament a value, use a += 1. to decrement a value, use− a -= 1.

What are the symbols of increment and decrement operators?

The decrement (–) and increment (++) operators are special types of operators used in programming languages to decrement and increment the value of the given variable by 1 (one), respectively.

What does ++ mean in JavaScript?

The increment operator ( ++ ) increments (adds one to) its operand and returns the value before or after the increment, depending on where the operator is placed.


3 Answers

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

final long oldValue = resultResponses;
final long newValue = ++resultResponses;
like image 73
Jesper Avatar answered Oct 04 '22 06:10

Jesper


Because the increment increases the value after it was assigned (Post-Increment). That's exactly what resultResponses++ is supposed to do.
If you want resultResponses to be 1, you need to use Pre-Increment, which is ++resultResponses

like image 40
Simon Woker Avatar answered Oct 04 '22 06:10

Simon Woker


If you want to increment oldValue before the assignment you will have to place ++ before the variable:

final long newValue = ++resultResponses;

This means that the increment takes place before the statement is executed instead of after.

like image 21
Jivings Avatar answered Oct 04 '22 04:10

Jivings