[英]Unsure about for-loop iteration?
So I'm new to programming in Java and I'm just having a hard time understanding why this 所以我是Java编程的新手,我很难理解为什么
for (int i = 0, j=0; i <10; i++) {
System.out.println(j += j++);
}
prints out 0 ten times? 打印0十次?
j += j++
can be thought of as 可以认为是
j = j + j++
Now, we start with j = 0
, so j++
increments j
and returns its old value of 0
(!), hence we essentially are left with 现在,我们开始与
j = 0
,那么j++
递增j
并返回的旧值0
,因此我们基本上只剩下(!),
j = 0 + 0
// ^ ^
// j j++
ten times. 十次。 The incrementation of
j
is overriden by the fact that we reassign j
to the outcome of the right hand side ( 0
) just after. j
的增加被以下事实覆盖:我们在紧随其后将j
重新分配给右侧( 0
)的结果。
Sometimes I find it helpful to look at the bytecode. 有时,我发现查看字节码会有所帮助。
j += j++
is really: j += j++
实际上是:
ILOAD 1 // load j, which is 0
ILOAD 1 // load j, which is 0
IINC 1 1 // j++
IADD // add top two stack elements
ISTORE 1 // store result back in j
Since IINC
does not alter the stack in any way, IADD
adds the value of j
to itself: 0 + 0
. 由于
IINC
不以任何方式改变堆栈, IADD
增加值j
本身: 0 + 0
。 This result is stored back into j
by ISTORE
after j
has been incremented by IINC
. 这一结果被存储回
j
通过ISTORE
后 j
已经递增IINC
。
In j += j++
you are actually doing 在
j += j++
您实际上正在做
j = j + j++;
so for j=0
you will get 所以对于
j=0
你会得到
j = 0 + j++
and since j++
will increment j
after returning its value you will get 并且由于
j++
将在返回j
的值后递增j
,因此您将获得
j = 0 + 0;
for now after j++
j will be equal to 1 but, after calculating 0+0
it will return to 0
and that value will be printed. 现在,在
j++
j将等于1,但是在计算0+0
,它将返回0
,并且将打印该值。
Are you unsure about the for-loop? 您不确定for循环吗? int i = 0 declares an int i, and sets it to 0. j = 0 also declares another int j, and sets it to 0. i < 10 states that while i is less than 10, the loop will keep on going.
int i = 0声明一个int i并将其设置为0。j = 0还声明另一个int j并将其设置为0。i <10表示尽管i小于10,循环仍将继续。 Finally, i++ states that every time the loop is done, i = i + 1, so essentially one will be added to i.
最后,i ++声明每次循环完成时,i = i + 1,因此本质上将一个加到i上。
System.out.println(++j);
代替
System.out.println(j += j++);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.