Java:增量/减量运算符的前缀/后缀? [英] Java: Prefix/postfix of increment/decrement operators?
问题描述
从下面的程序或这里,为什么最后一次打电话给 System.out.println(i)
打印值 7
?
From the program below or here, why does the last call to System.out.println(i)
print the value 7
?
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}
推荐答案
i = 5;
System.out.println(++i); //6
这打印出6,因为它需要我添加一个并返回值。 5 + 1 = 6;这是前缀,在操作中使用前添加数字。
This prints out "6" because it takes i adds one to it and returns the value. 5+1=6; This is prefixing, adding to the number before using it in the operation.
i = 6;
System.out.println(i++); //6 (i = 7, prints 6)
这打印出6,因为它需要我,存储副本,添加1并返回副本。所以你得到了我的价值,但也同时增加了它。因此,您打印旧值但它会增加。后缀增量的美妙。
This prints out "6" because it takes i, stores a copy, adds 1 and returns the copy. So you get the value that i was, but also increment it at the same time. Therefore you print out the old value but it gets incremented. The beautfy of a postfix increment.
然后当你打印出i时,它显示了i的实际值,因为它已经增加了。 7
Then when you print out i, it shows the real value of i because it had been incremented. 7
这篇关于Java:增量/减量运算符的前缀/后缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!