JavaRanch Home    
 
This page:         last edited 03 December 2012         What's Changed?         Edit

Post Increment Operator And Assignment   

The code
int i = 0;
i = i++;
System.out.println(i);
produces the output "0" instead of "1". Why?



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

  1. "i++" is evaluated. The value of "i++" is the value of i before the increment happens.
  2. As part of the evaluation of "i++", i is incremented by one. Now i has the value of 1;
  3. The assignment is executed. i is assigned the value of "i++", which is the value of i before the increment - that is, 0.

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

int oldValue = i; 
i = i + 1;
i = oldValue; 

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

i++;

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


JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton