java-8assignment-operatorpost-increment

How is line 2 is evaluated?


int f = 1;
f = f++;
System.out.println(f);

post increment operator is having a higher precedence than assignment operator so i suppose value of f (that is 1) is used for assignment and f is incremented then the output would be 2 (as value of f is now 2) but the output is 1, but how? where am i wrong?

my explanation results in right answer in the code below

int f = 1;
int g = f++;
System.out.println(f);

output is 2 in this case.


Solution

  • You can't assign a value to a variable before you evaluate the value. Hence you must evaluate f++ first. And since f++ returns 1, that's the value assigned to f, which overwrites the incremented value of f.

    Your second snippet is a completely different scenario, since you assign the value of f++ to a different variable, so the incremented value of f is not overwritten.