Java中的增量前和增量后行为 [英] Pre-increment and post-increment behavior in Java

查看:72
本文介绍了Java中的增量前和增量后行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释以下代码的实现吗?

Can someone explain the implementation of the following code:

int j = 1;
System.out.println(j-- + (++j / j++));

我期望输出为3,如下所示: 由于"/"的优先级比"+"的优先级高,因此将首先对其进行评估.

I'm expecting the output to be 3 as explained below: Since '/' has higher precedence than '+' it is evaluated first.

op1 = ++j (Since it is pre-increment, the value is 2, and j is 2)
op2 = j++ (Since it is post-increment, 2 is assigned and j is incremented to 3)

因此,在括号内执行"/"运算的结果为2/2 = 1. 然后是"+"操作:

So the result of the '/' operation within parantheses is 2 / 2 = 1. Then comes the '+' operation:

op1 = j-- (Since it is Post-increment, the value is 3, and j is decremented to 2)
op2 = 1 (The result of the '/' was 1)

因此,结果应为3 +1 = 4. 但是当我评估这个表达式时,我得到了2.这是怎么发生的?

So, the result should be 3 + 1 = 4. But when I evaluate this expression, I'm getting 2. How come this happen?

推荐答案

由于'/'的优先级高于'+'的优先级,因此先进行评估.

Since '/' has higher precedence than '+' it is evaluated first.

否,表达式是从左到右求值的-然后使用优先级规则将每个操作数关联起来.

No, expressions are evaluated left to right - each operand is then associated using precedence rules.

因此您的代码等同于:

int temp1 = j--; //1
int temp2 = ++j; //1
int temp3 = j++; //1
int result = temp1 + (temp2 / temp3); //2

这篇关于Java中的增量前和增量后行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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