2

Let's say we have following

Integer a = 0;
a = a++;
System.debug(a)

why it shows 0?

2 Answers 2

11

Incrementing modifies in place. You don't need to reassign at all. However, using the ++a operator returns the value after increment, as opposed to the a++ operator, which returns the value before increment.

0
7

Speaking from a technical point of view, with the postfix operator, the compiler basically does this internally:

temp = a; // rvalue storage
a = a + 1; // ++ operator
a = temp; // lvalue assignment

As Adrian says, you shouldn't assign the value, as the prefix and postfix ++ and -- operators modify the variable being referenced.

Using a prefix operator (a = ++a) would change it to:

a = a + 1; // ++ operator
temp = a; // rvalue storage
a = temp; // lvalue assignment

You should generally not use a prefix or postfix operator on the variable being assigned to (the lvalue); in practice, the increment and decrement operators are typically used to modify an accumulator or counter, not modify the value currently being assigned to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.