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.
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.
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.
++expr --expr +expr -expr ~ !
* / %
<< >> >>>
< > <= >= instanceof
= += -= *= /= %= &= ^= |= <<= >>= >>>=