简体   繁体   English

java表达式计算和运算符优先级

[英]java expression calculation and operator precedence

i have problem to step by step java expression calculation我有问题一步一步的java表达式计算

System.out.println(++x + x++ * y-- - --y);

I know this precedence: 1. postfix unary 2. prefix unary 3. multiplicative 4. additive我知道这个优先级:1. 后缀一元 2. 前缀一元 3. 乘法 4. 加法

but when i calculate with this precedence the result is below: // 12 + 11 * 19 - 18 can some one help me但是当我用这个优先级计算时,结果如下:// 12 + 11 * 19 - 18 有人可以帮我吗

You can understand it from the example given below:你可以从下面给出的例子中理解它:

public class Main {
    public static void main(String[] args) {
        int x = 5, y = 10;
        System.out.println(++x + x++ * y-- - --y);// 6 + 6 * 10 - 8 = 58
    }
}

Steps in this calculation:此计算的步骤:

  1. ++x = 6
  2. 6 + x++ * y-- = 6 + 6 * 10 = 6 + 60 = 66 (after this y will become 9 because of y-- and x will become 7 because of x++ but this increased value of x has never been used in subsequent calculation) 6 + x++ * y-- = 6 + 6 * 10 = 6 + 60 = 66 (在此之后y将成为9由于y--x将成为7由于x++但该增加的值x从未在使用后续计算)
  3. 66 - 8 = 58 (before y gets subtracted from 66 , it will become 8 because of --y ) 66 - 8 = 58 (在从66减去y之前,它会变成8因为--y

Postfix unary is applied after the variable evaluation, opposite to prefix, which is applied before evaluation, your expression can be rewrited:后缀一元在变量求值后应用,与在求值前应用的前缀相反,您的表达式可以重写:

int x_prefix = x + 1; // ++x
int y_prefix = y - 1; // --y

System.out.println(x_prefix + x * y - y_prefix);

int x = x + 1; // x++
int y = y - 1; // y--

You write operators precedence, it's right but every operator has own behavior, in case of postfix increment, of course has to be evaluate before others, but its behavior is return the current variable and after increment its value.您编写运算符优先级,这是正确的,但每个运算符都有自己的行为,在后缀增量的情况下,当然必须在其他运算符之前进行评估,但其行为是返回当前变量并在增加其值之后。

NOTE: I just rewrited your expression as is, if you use in the same expression the variable postfix incremented, the next access see the variable incremented:注意:我只是按原样重写了您的表达式,如果您在同一个表达式中使用变量后缀递增,则下一次访问会看到变量递增:

int x = 1;

System.out.println(x++ + x++); // 1 + 2
System.out.println(x) // 3

For completeness:为了完整性:

int x = 1;

System.out.println(++x + ++x); // 2 + 3
System.out.println(x) // 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM