Java - What is the value of i for the statement: int i = 15; i = i++;

Question

What will be the value of i after this assignment?

int i = 15; 
i = i++; 


Click to view the answer

15

Explanation

Here is the explanation of how the expression is evaluated.

Because i++ uses a post-fix increment operator, the current value of i is used in the expression.

The current value of i is 15. The expression becomes i = 15.

The value of i is incremented by 1 in memory as the second effect of i++.

At this point, the value of i is 16 in memory.

The expression i = 15 is evaluated and the value 15 is assigned to i.

The value of the variable i in memory is 15 and that is the final value.

i has a value 16 in the previous step, but this step overwrote that value with 15.

Therefore, the final value of the variable i after i = i++ is executed will be 15, not 16.

Demo

public class Main {
  public static void main(String[] args) {
    int i = 15; /*from   w  w w . j a v a2  s  .c om*/
    i = i++; 
    System.out.println(i);
  }
}

Result

Related Quiz