Didn't understand the answer of this piece of code (java)
Look at the expression:
i = i++ + f1(i);
Here you need to understand what exactly does and returns i++
: it increments i
, but returns the old value i
. Therefore, if i == 0
, then i++
increments i
by 1
, but the resulting value of the expression 0
.
In Java, expressions are evaluated from left to right. So, in the above expression, it evaluates first i++
and then f1(i)
.
After i++
, i == 1
therefore f1(i)
actually f1(1)
. This method prints the value i
that 1
, with a comma after it, and returns 0
.
Since it i++
returns the old value i
(before it is incremented), the expression becomes:
i = 0 + 0;
The first 0
is the result i++
, the second 0
is the result f1(i)
. Thus, it is i
assigned 0
. Finally, you print the value i
.
source to share