Quiz Time - 5 Jan 2023

A Java Gotcha - Post Increment/Decrement Operators

Subscribe for our daily quizz!


 

The possibly unexpected answer to the above is C. This is one of those trick questions they like to ask in certification exams or interviews. To understand why the answer is C and not A one needs to appreciate what the operators do.  This type of "trivia" is often glossed over when one is learning Java but having a solid understanding of what is going on turns one from a mediocre programmer to a great programmer. Our Java Essentials course makes sure we cover all these bases.

Post Increment/Decrement Operators Sequence

The post increment operator (x++) will return the value of the operand then increment it while the pre increment (++x)  will increase the value then return it.

So by the time we get to "return x++", the original value of x = 10 would have been reduced to 9 by the "x--" statement. This statement would have reduced x to 9 and then returned 9 but it wasn't assigned to anything but x was updated. So when we get to "return x++" it first supplies the value of x which is 9 to the return statement and then increments x. Incrementing X no effect as function has returned and the x parameter is now out-of-scope.

Incomplete Explanation - Operator Precedence

​​​​​​​ Often people refer to operator precedence when dealing with this question but the post-increment/decrement and pre-increment/pre-decrement operators have a very high precedence and therefore this doesn't explain the observed behaviour. 

Java Operator Precedence Table

​​​​​​​

Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Blogs