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"因为它需要 i,加一,然后返回值: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"因为它需要 i,存储一个副本,给变量加 1,然后返回副本.所以你得到了 i 的值,但同时也增加了它.因此,您打印出旧值,但它会增加.后缀增量的美妙之处.
This prints out "6" because it takes i, stores a copy, adds 1 to the variable, and then 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 beauty 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屋!