如何在复杂表达式中计算java增量语句 [英] How are java increment statements evaluated in complex expressions

查看:168
本文介绍了如何在复杂表达式中计算java增量语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码的输出是什么:

What is the output of the following code:

int x = 2;  
x += x++ * x++ * x++;  
System.out.println(x);  

我知道 ++ variableName 是预先的-increment运算符和 variableName 的值在表达式中使用之前递增,而 variableName ++ 在之后递增其值表达式被执行。我想知道的是 - 这个逻辑在这里是如何应用的?

I understand that ++variableName is pre-increment operator and the value of variableName is incremented before it is used in the expression whereas variableName++ increments its value after the expression is executed. What I want to know is - how does this logic apply here?

推荐答案

更容易看到x发生了什么= 1而不是2. x = 1 的输出为7.

Its easier to see the what is going on with x = 1 instead of 2. The output for x=1 is 7.

理解这一点的关键在JLS 15.7.2 表示在执行操作的任何部分之前完全评估每个操作数。

The key to the understanding of this is in JLS 15.7.2 which states that the every operand is fully evaluated before any part of the operation is performed.


Java编程语言保证在执行操作本身的任何部分之前,运算符的每个操作数(条件运算符&&,||和?:)除外似乎都是完全计算的。

The Java programming language guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

因此,评估x ++(每次3次,从左到右,具有适当的优先级,这不是问题),然后评估操作*并将其分配给原始值。 / p>

Thus, x++ (each of 3 times, left to right with appropriate precedence which isn't an issue here) is evaluated, then the operation * is evaluated and assigned to the original value.

x = 1 + (1 * 2 * 3)

如果x以2开头,则得到:

If x starts out with 2, you get:

x = 2 + (2 * 3 * 4)

与C不同,它在Java中定义良好,并且在任何运行时的每次调用中都会表现相同。

Unlike in C, this is well defined in Java and will behave the same on each invocation in any runtime.

如果有人想自己运行它,那么关联的想法: https://ideone.com/Y2qcJ6

这篇关于如何在复杂表达式中计算java增量语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆