Java 中的优先级

Precedence in Java

一元后缀递增和递减运算符根据优先级比关系运算符具有更高的优先级table,所以为什么在这样的表达式中 (x++ >=10) 关系运算符先求值然后变量递增?

关系运算符在递增前不计算。

首先计算关系运算符(x++10)的操作数。

然而,x++ 的评估增加 x 但 returns x 的原始值,所以即使增加已经发生,值传递给关系运算符是 x.

的原始值

不首先评估运算符。顺序是:

  • Evaluate LHS (x++) - 结果是x的原始值,然后x递增
  • 计算 RHS (10) - 结果是 10
  • 比较 LHS 和 RHS 的结果

下面是演示代码:

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;
    }
}

打印出 10 然后 false,因为在计算 RHS 时 x 已经 增加了...但是>= 运算符仍在评估 9 >= 10,因为表达式 x++ 的结果是 x 原始 值,而不是增量值一.

如果您想要 递增后的结果,请改用 ++x

你的结论不正确。 x++ 是先计算的,只是它的值是为后缀增量操作定义的增量之前 x 的值。

因为这就是“++、--”的工作方式。如果它出现在变量之后,则使用旧值然后值增加,如果它出现在变量之前,则先增加,然后使用新值。 所以,如果你想在增加它的值之后检查它之前使用变量,那么使用(++x >= 10),或者在没有引用的情况下增加它然后检查它,就像这样:

int x = 0;
x++;
if(x >= 10) {...}

一元运算符

无论您如何将 一元运算符 放在表达式中,以下 table 总结了它的用法。

+----------+-------------------+------------+-----------------------------------------------------------------------------------+
| Operator |       Name        | Expression |                                    Description                                    |
+----------+-------------------+------------+-----------------------------------------------------------------------------------+
| ++       | prefix increment  | ++a        | Increment "a" by 1, then use the new value of "a" in the residing expression.     |
| ++       | postfix increment | a++        | Use the current value of "a" in the residing expression, then increment "a" by 1. |
| --       | prefix decrement  | --b        | Decrement "b" by 1, then use the new value of "b" in the residing expression.     |
| --       | postfix decrement | b--        | Use the current value of "b" in the residing expression, then decrement "b" by 1. |
+----------+-------------------+------------+-----------------------------------------------------------------------------------+

然后,考虑以下 java 程序:

public class UnaryOperators {
    public static void main(String args[]) {
        int n;

        // postfix unary operators
        n = 10;
        System.out.println(n); // prints 10
        System.out.println(n++); // prints 10, then increment by 1
        System.out.println(n); // prints 11

        n = 10;
        System.out.println(n); // prints 10
        System.out.println(n--); // prints 10, then decrement by 1
        System.out.println(n); // prints 9


        // prefix unary operators
        n = 10;
        System.out.println(n); // prints 10
        System.out.println(++n); // increment by 1, then prints 11
        System.out.println(n); // prints 11

        n = 10;
        System.out.println(n); // prints 10
        System.out.println(--n); // decrement by 1, then prints 9
        System.out.println(n); // prints 9
    }
}