Reputation: 733
public class I {
public static void main(String args[])
{
int i=0,j=1,k=2;
i=i++ - --j + ++k;
System.out.println("\ni : "+i+"\nj : "+j+"\nk : "+k);
}
}
Can anyone please explain to me Why the above code gives output :
i : 3
j : 0
k : 3
Instead of giving the output :
i : 4
j : 0
k : 3
?
Upvotes: 0
Views: 182
Reputation: 13139
Therefore: i : 3.
Upvotes: 3
Reputation: 14053
The value of i
is 3
because the expression is evaluated like that:
i++ //still equals 0 since it's incremented after the evaluation
-
--j // equals 0 too since it's decremented is done before the evaluation
+
++k // equals 3 since it's incremented before the evaluation
Upvotes: 1
Reputation: 375
Hence, i is 3, j is 0 and k is 3.
Upvotes: 1
Reputation: 111027
This is because of the difference between post increment and pre increment operators.
Pre increment comes before the variable (e.g. ++i
) and post increment comes after the variable (e.g. i++
).
Break it down into smaller parts:
i++ // post increment means increment AFTER we evaluate it
// expression evaluates to 0, then increment i by 1
--j // pre decrement means decrement BEFORE evaluation
// j becomes 0, expression evaluates to 0
++k // pre increment means increment BEFORE evaluation
// k becomes 3, expression evaluates to 3
So now we have:
i = 0 - 0 + 3 // even though i was set to 1, we reassign it here, so it's now 3
Upvotes: 1
Reputation: 92274
Here's what the line in question produces, Remember that if i
is 0, then i++ == 0
and ++i == 1
i = i++ - --j + ++k;
i = (0) - (-0) + (3) // i is 3
Upvotes: 1
Reputation: 55213
I'm guessing your confusion hinges on the use of i++
- but the side effect of i++
incrementing i
has no effect, since i
is reassigned the result of the "complicated expression".
Upvotes: 1