When i run the following example i get the output 0,2,1
class ZiggyTest2{
static int f1(int i) {
System.out.print(i + ",");
return 0;
}
public static void main(String[] args) {
int i = 0;
int j = 0;
j = i++; //After this statement j=0 i=1
j = j + f1(j); //After this statement j=0 i=1
i = i++ + f1(i); //i++ means i is now 2. The call f1(2) prints 2 but returns 0 so i=2 and j=0
System.out.println(i); //prints 2?
}
}
I don't understand why the output is 0,2,1 and not 0,2,2
Hope this explaination might be of some help :
Do try this
So in short during post increment, expression is first solved and then value is incremented. But in pre increment, value is first incremented and then expression is solved.
But if you write only
Then both means the same thing.
Regards
To get In-depth you need to see Expression and its Evaluation Order
Here's little explanation about equation i++ + f1(i) evaluation
In Equation Compiler get "i" which is Equals to 1 and put it on stack as first operand then increments "i", so its value would be 2, and calculates second operand by calling function which would be 0 and at the time of operation (+) execution operands would be 1 and 0.
If we expand
i = i++ + f1(i)
statement, we get something like followingI guess main steps can be summarized like above.
In Post increment operator value will of operand will increase after use. Example
First k (value = 1) is assigned with l after that the k value will increase
Similarly thing happens in the following line
Pre increment means: add one to variable and return incremented value; Post increment - first return i, then increment it;
i++
meansi
is now2
. The callf1(i)
prints2
but returns 0 soi=2
andj=0
before this
i = 1
, now imaginef1()
called and replaced with 0so
now it would be
In Simpler words (from here @ Piotr )
Another such Example :