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
.
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.
Python does not have unary increment/decrement operator( ++/--). Instead to increament a value, use a += 1. to decrement a value, use− a -= 1.
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.
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.
The postfix ++
operator returns the old value (before incrementing). You want to use prefix ++
:
final long oldValue = resultResponses;
final long newValue = ++resultResponses;
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With