What is the logic behind this behaviour?
int i=0;
for(int k=0;k<10;k++){
i++;
}
System.out.println("i="+i);
Output=10; //Exepcted
int i=0;
for(int k=0;k<10;k++){
i=i++;
}
System.out.println("i="+i);
Output=0; //Surprised :)
Can anybody throw some light on above functionality?
Increment in java is performed in two ways, 1) Post-Increment (i++): we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1. 2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement.
Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated.
The only difference is the order of operations between the increment of the variable and the value the operator returns. So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented.
There is no difference in your case. --i is pre-decrement and i-- is post-decrement.
See this brilliant answer:
x = x++;
is equivalent to
int tmp = x;
x++;
x = tmp;
From this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With