Search code examples
javaincrementoperator-precedence

Precedence in Java


Unary postfix increment and decrement operators have more preceedence than relational operators according to precedence table, so why in a expression like this (x++ >=10) the relational operator evaluated first and then the variable is incremented?


Solution

  • The operator isn't evaluated first. The ordering is:

    • Evaluate LHS (x++) - the result is the original value of x, then x is incremented
    • Evaluate RHS (10) - the result is 10
    • Compare the results of the LHS and RHS

    Here's code to demonstrate that:

    public class Test {
    
        static int x = 9;
    
        public static void main(String[] args) {
            boolean result = x++ >= showXAndReturn10();
            System.out.println(result); // False
        }
    
        private static int showXAndReturn10() {
            System.out.println(x); // 10
            return 10;
        }
    }
    

    That prints out 10 then false, because by the time the RHS is evaluated x has been incremented... but the >= operator is still evaluating 9 >= 10 as the result of the expression x++ is the original value of x, not the incremented one.

    If you want the result after incrementing, use ++x instead.