Java:pre,postfix操作符优先
我对
Java中的运算符优先级有两个类似的问题.
第一: int X = 10; System.out.println(X++ * ++X * X++); //it prints 1440 根据Oracle tutorial: 所以,我想这个评估顺序: 1) first postfix operator: X++ 1.a) X++ "replaced" by 10 1.b) X incremented by one: 10+1=11 At this step it should look like: System.out.println(10 * ++X * X++),X = 11; 2) second POSTfix operator: X++ 2.a) X++ "replaced" by 11 2.b) X incremented by one: 11+1=12 At this step it should look like: System.out.println(10 * ++X * 11),X = 12; 3) prefix operator: ++X 3.a) X incremented by one: 12+1=13 3.b) ++X "replaced" by 13 At this step it should look like: System.out.println(10 * 13 * 11),X = 13; 4) evaluating 10*13 = 130,130*11 = 1430. 但Java似乎忽略了PRE / POST排序,并将它们放在一个层次上.所以真正的订单: X++ -> ++X -> X++ 什么原因导致答案(10 * 12 * 12)= 1440. 第二个: Example from this question: int a=1,b=2; a = b + a++; 部分答案: 好的,让我们一步一步看看: 1) replacing "b" with 2 2) replacing "a++" with 1 3) incrementing "a" by 1 -> at this point a==2 4) evaluating 2+1 = 3 5) overwriting incremented value of "a" with 3 似乎一切都很好. a += b + a++; 步骤1-4应与上述相同. a += 3; 其中a == 2 然后我想:OK,a = 2 3,所以一个应该是5.但答案只有4 我真的很困惑我已经花了几个小时,但仍然不明白我在哪里错了. 附:我知道,我不应该在实际应用中使用这种“风格”.我只是想了解我的想法有什么问题. 解决方法
这个混乱来自于从左到右评估操作数的事实.在操作者优先级/操作顺序受到任何关注之前,首先进行操作.
此行为在JLS 15.7.2. Evaluate Operands before Operation中指定 所以X * X * X首先被评估为10 * 12 * 12,如您所见,1440得出. 为了说服自己,请考虑以下几点: X = 10; System.out.println(X++ * ++X); X = 10; System.out.println(++X * X++); 如果X先完成,则X秒,然后乘法,都应该打印相同的数字. 但他们没有: X = 10; System.out.println(X++ * ++X); // 120 X = 10; System.out.println(++X * X++); // 121 那么这有什么意义呢?那么如果我们意识到操作数是从左到右进行评估的,那么这是完全正确的. X = 10; System.out.println(X++ * ++X); // 120 (10 * 12) X = 10; System.out.println(++X * X++); // 121 (11 * 11) 第一行看起来像 X++ * ++X 10 (X=11) * (X=12) 12 10 * 12 = 120 和第二 ++X * X++ (X=11) 11 * 11 (X=12) 11 * 11 = 121 那么为什么前缀和后缀增加/减量运算符在表中? 的确,增量和减量必须在乘法之前执行.但是呢是说: Y = A * B++ // Should be interpreted as Y = A * (B++) // and not Y = (A * B)++ 就像 Y = A + B * C // Should be interpreted as Y = A + (B * C) // and not Y = (A + B) * C 仍然是操作数的评估顺序是从左到右. 如果你还没有获胜: 考虑以下程序: class Test { public static int a(){ System.out.println("a"); return 2; } public static int b(){ System.out.println("b"); return 3; } public static int c(){ System.out.println("c"); return 4; } public static void main(String[] args) { System.out.println(a() + b() * c()); // Lets make it even more explicit System.out.println(a() + (b() * c())); } } 如果这些论据在需要时进行评估,那么b或c将会先到,另一个是最后一个.但是,程序输出: a b c 14 a b c 14 因为,无论在方程式中需要和使用的顺序如何,它们仍然从左到右进行评估. 有用阅读: > What are the rules for evaluation order in Java? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |