1
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.

Eran
  • 387,369
  • 54
  • 702
  • 768
Jilson
  • 569
  • 5
  • 11

1 Answers1

8

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • To get output 2 @Jilson need to put pre increment like f = ++f; am i right ? – Sudhir Ojha Jun 07 '18 at 05:48
  • 2
    @SudhirOjha that would work, since `++f` will return 2. Of course, there's no reason to assign the value of either `++f` or `f++` back to `f`. – Eran Jun 07 '18 at 05:49
  • 1
    There seems to be a common misunderstanding what “higher precedence” means. Actually, the OP is right in that the post increment operator has a higher precedence than assignment operator. but that just means that it is evaluated *before* the assignment, so the subsequent assignment cancels its side effect. The OP seems to assume that the increment will happen after the assignment, but that would contradict the precedence rule. – Holger Jun 07 '18 at 07:49