Java预增和后增运算符 [英] Java preincrement and postincrement operators
问题描述
public class Sample
{
public static void main(String[] args) throws Exception
{
//part 1
int i=1;
i=i++;
i=++i;
i=i++;
System.out.println(i);
//part 2
i=1;
int a=i++;
a=++i;
a=i++;
System.out.println(a+"\n"+i);
}
}
输出
2
3
4
Output
2
3
4
昨天我的朋友问了这个问题.我对此有些困惑. 第1部分将 i 值打印为 2 .帖子增量在这里不起作用.但是在第2部分中,它可以工作.我可以理解第2部分,但对第1部分感到困惑.实际如何运作?有人能让我明白吗?
Yesterday my friend asked this question. I little bit confused about this. part 1 prints the i value as 2. Post increment is not working here. But in the part 2, it works. I can understand the part 2 but i have confused in part 1. How actually it works? Can anybody make me understand?
推荐答案
第一部分应打印i = 2
.这是因为:
Part one should print i = 2
. This is because:
public class Sample
{
public static void main(String[] args) throws Exception
{
//part 1
int i=1;
// i++ means i is returned (which is i = 1), then incremented,
// therefore i = 1 because i is incremented to 2, but then reset
// to 1 (i's initial value)
i=i++;
// i is incremented, then returned, therefore i = 2
i=++i;
// again, first i is returned, then incremented, therefore i = 2
// (see first statement)
i=i++;
System.out.println(i);
//part 2
i=1;
// first i is returned then incremented, so i = 2, a = 1
int a=i++;
// i is incremented then returned, so i = 3 and a = 3
a=++i;
// i is first returned, then incremented, so a = 3 and i = 4
a=i++;
System.out.println(a+"\n"+i);
}
}
也许最简单的理解方法是引入一些额外的变量.这是您拥有的:
Perhaps the simplest way to understand this is to introduce some extra variables. Here is what you have:
// i = i++
temp = i;
i = i + 1;
i = temp; // so i equals the initial value of i (not the incremented value)
// i = ++i;
i = i + 1;
temp = i;
i = temp; // which is i + 1
// i = i++
temp = i;
i = i + 1;
i = temp; // so i equals the previous value of i (not i + 1)
请注意设置temp
变量时的顺序不同-增量是之前还是之后,具体取决于它是后增量( i++
)或预递增(++i
).
Notice the difference in order of when the temp
variable is set--either before or after the increment depending on whether or not it's a post-increment (i++
) or a pre-increment (++i
).
这篇关于Java预增和后增运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!