-4

Lets say I got this piece of code:

public class Incrementor {

    private int i;

    public int getInt(){
        return i;
    }

    private void incrementA(){
        i = i+1;
    }

    private void incrementB(){
        i = i++;
    }
}
  • When I call incrementA() before calling getInt() the value will be 1.
  • When I call incrementB() before calling getInt() the value will be 0.
elp
  • 840
  • 3
  • 12
  • 36

3 Answers3

5

The assignment

i = i++;

is basically equivalent to

// These two lines corresponds to i++
int temporary_variable = i;
i = i + 1;

// This line is your assignment back to i
i = temporary_variable;

The postfix ++ operator returns the old value, before incrementing.

If all you want to do is increment the variable, no assignment is needed as it's built into the ++ operation itself:

private void incrementB(){
    i++;  // Increment i by one
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
4

i++ returns the value of i before the increment happened. The code i = i++ is equal to i = i.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
3
    i = i++;

While this syntax is perfectly valid, it isn't doing what you think. It should just be:

    i++;

i++ is a post-increment operator, meaning it returns the value of i prior to being incremented when used as the right hand side of an expression.

Ben R.
  • 1,965
  • 1
  • 13
  • 23
  • 1
    "The syntax here is wrong" The syntax is fine. It's just that it doesn't do anything that you would ever need. – Andy Turner Jan 07 '19 at 11:52
  • True - I meant his syntax was wrong for what he wanted to achieve. You're correct, it's perfectly valid. – Ben R. Jan 07 '19 at 12:14