Post Increment Operator And Assignment (Wiki forum at Coderanch) (original) (raw)

Why does this code produce the output "0" instead of "1"?


Let's take a close look at what the line "i = i++;" does:

That is, "i = i++" roughly translates to

With other words, it is a common misconception that the increment is happening last. The increment is executed immediately when the expression gets evaluated, and the value before the increment is remembered for future use inside the same statement.

Solution:

You don't need the assignment at all, just use

Reason:

The post-increment operator increments the value of your integer "i" after the execution of your "System.out..." statement so use "++i" (pre-increment operator)..


See also