0

In this code segment,

[1]int i=0;
[2]i = i++; 
[3]System.out.println(i);

In line 2, it is executed the expression first (which is assigned 0 to i) and then it should increment the value by 1.

In System.out.println(i) , I am getting the answer as 0 instead of 1.Can someone explain the reason for this?

prime
  • 14,464
  • 14
  • 99
  • 131
chathura
  • 3,362
  • 6
  • 41
  • 68

3 Answers3

2

i++ does not yield a variable, but a value.

  1. i++ yields 0.

  2. Then i is incremented to 1.

  3. Then 0 is assigned to i.

Summary: the precedence of operators is maybe not what you expected. Or at least you might've misunderstood where the actual increment of i is happening. It's normal to show people that use of i++ can be split into 2 lines where the line after is doing the incrementation - that's not always correct. It happens before the assignment operator.

Xabster
  • 3,710
  • 15
  • 21
0

The assignment first saves the value of i, then sets i to its value plus 1, and, finally, resets i back to its original value. Kind of:

int temp=i;
i=i+1;
i=temp;
Lavinia
  • 11
  • 2
-1

@chathura2020 : go to this link.It is about Sequence points.

Sequence points also come into play when the same variable is modified more than once within a single expression. An often-cited example is the C expression i=i++ , which apparently both assigns i its previous value and increments i. The final value of i is ambiguous, because, depending on the order of expression evaluation, the increment may occur before, after, or interleaved with the assignment. The definition of a particular language might specify one of the possible behaviors or simply say the behavior is undefined. In C and C++, evaluating such an expression yields undefined behavior.

(This is not true for java)

prime
  • 14,464
  • 14
  • 99
  • 131
  • 1
    Your answer is correct for C but incorrect for Java. The statement `i = i++;` always has a [consistent meaning in Java](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.7). Please modify your answer. – Nayuki Aug 10 '13 at 15:43
  • @Nayuki Minase : Thanks for your comment. So what will be the answer for the original question ? – prime Aug 10 '13 at 19:47
  • [this](http://www.coderanch.com/how-to/java/PostIncrementOperatorAndAssignment) has the solution for the very same problem. and there are no sequence-points in Java. Order of evaluation (etc) is well defined in Java. – prime Aug 10 '13 at 20:06