Home > Software design >  In Java,operator precedence, increment and decrement, why isn't the first println statement exe
In Java,operator precedence, increment and decrement, why isn't the first println statement exe

Time:10-02

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?

CodePudding user response:

The operands of an expression are evaluated left to right.

In the expression x == x, first x is evaluated. It increments x by 1, but returns the original value of x. So x returns 99.

Then x is evaluated, which returns 100 (since it was incremented by x ).

Since 99 is not equal to 100, this condition evaluates to false.

If you change the expression to x==x , you'll get true.

CodePudding user response:

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 thus x == 100
  • Get x = 100 as the right operand (note it is already incremented)
  • 100 != 99

Following the shippet x == x means following:

  • Analyze expression from left to the right
  • Get x = 99 as the left operand
  • Increment x and thus x == 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.

  •  Tags:  
  • java
  • Related