java中的preincrement / postincrement [英] preincrement / postincrement in java
本文介绍了java中的preincrement / postincrement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有些人可以帮助我理解原因:
Can someome help me to understand why:
int i=1;
int j=1;
int k=1;
int l=1;
System.out.println(i++ + i++);
System.out.println(++j + ++j);
System.out.println(k++ + ++k);
System.out.println(++l + l++);
给:
3
5
4
4
3
5
4
4
推荐答案
变量++表示:增量变量AFTER评估表达式。
Variable++ means: Increment variable AFTER evaluating the expression.
++变量意味着:在计算表达式之前增加变量。
++Variable means: Increment variable BEFORE evaluating the expression.
这意味着,将您的示例翻译为数字:
That means, to translate your example to numbers:
System.out.println(i++ + i++); //1 + 2
System.out.println(++j + ++j); //2 + 3
System.out.println(k++ + ++k); //1 + 3
System.out.println(++l + l++); //2 + 2
这是否清楚,还是需要进一步解释?
Does this clear things up, or do you need further explanations?
需要注意的是:'println'之后所有这些变量的值等于'3'。
To be noted: The value of all those variables after the 'println' equal '3'.
自OP以来问,这里有一个用例,这个行为实际上有用。
Since the OP asked, here's a little 'use-case', on where this behaviour is actually useful.
int i = 0;
while(++i < 5) { //Checks 1 < 5, 2 < 5, 3 < 5, 4 < 5, 5 < 5 -> break. Four runs
System.out.println(i); //Outputs 1, 2, 3, 4 (not 5)
}
与:
int i = 0;
while(i++ < 5) { //Checks 0 < 5, 1 < 5, 2 < 5, 3 < 5, 4 < 5, 5 < 5 -> break. Five runs
System.out.println(i); //Outputs 1, 2, 3, 4, 5
}
这篇关于java中的preincrement / postincrement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文