Issue
class Example{
public static void main(String args[]){
int x=99;
if(x++==x){
System.out.println("x++==x : "+x); //Why this code line is not run?
}
if(++x==x ){
System.out.println("++x==x : "+x);
}
}
}
Why isn't the first println
statement executed?
Solution
The differece between i++
and ++i
is very simple.
i++
- means exactly first get the value and then increment it for the further usage++i
- means exactly first increment the value and use the incremented value
Following the shippet x++ == x
means following:
- Analyze expression from left to the right
- Get
x = 99
as the left operand and use it in the expression - Increment
x
and thusx == 100
- Get
x = 100
as the right operand (note it is already incremented) 99 != 100
Following the shippet ++x == x
means following:
- Analyze expression from left to the right
- Get
x = 99
as the left operand - Increment
x
and thusx == 100
and use it in the expression - Get
x = 100
as the right operand (note it is already incremented) 100 == 100
You can see all these logic. E.g. not experienced developer cannot know these details. Therefore the best practice is to avoid such increments in the expression. Just do it before the expression in the single line. In this case the logic will be straight forward and you get much less problems.
Answered By - oleg.cherednik
Answer Checked By - Marilyn (JavaFixing Volunteer)