Search code examples
javaincrementprimitive

Assigning and incrementing a value during method call


Can anyone explain me why such call doesn't increment my i value ?

int i = 0;
list.get(7 + (i = i++));
list.get(7 + (i = i++));

it leaves i=0 instead of increment by one at least such that in the second call it is 1.


Solution

  • i = i++ is like doing:

    int old_i = i; 
    i = i + 1;
    i = old_i; 
    

    What is actually happening is that the value of i++ is the value of i before the increment happens, then i will get the value of.. i.

    In one line i++ will use the old value of i and then it will increment it.