[英]Precedence in Java
根據優先級表,一元postfix遞增和遞減運算符比關系運算符具有更多的優先級,那么為什么在這樣的表達式(x ++> = 10)中,關系運算符首先求值,然后變量遞增?
不首先評估操作員。 訂購是:
x++
) - 結果是x
的原始值,然后x
遞增 10
) - 結果是10 這是用於演示以下內容的代碼:
public class Test {
static int x = 9;
public static void main(String[] args) {
boolean result = x++ >= showXAndReturn10();
System.out.println(result); // False
}
private static int showXAndReturn10() {
System.out.println(x); // 10
return 10;
}
}
打印出10
然后false
,因為由時間RHS被評估x
已遞增...但是>=
操作者仍然在評估9 >= 10
作為表達式的結果x++
是原始值x
,而不是增加一個。
如果想在增量后得到結果,請改用++x
。
在增量之前不評估關系運算符。
首先評估關系運算符( x++
和10
)的操作數。
然而,評價x++
增量x
,但返回的原始值x
,所以盡管增量已經發生,傳遞給關系運算符的值是原始值x
。
你的結論是不正確的。 x ++被評估為第一個,只是它的值是在為后綴增量操作定義的增量之前的x值。
因為這就是“++, - ”的工作原理。 如果它在變量之后,則使用舊值,然后值增加,如果它在變量之前,則首先發生增量,然后使用新值。 因此,如果您想在增加其值之后使用該變量並在檢查之前使用該變量,則使用(++ x> = 10),或者在沒有引用的情況下增加它,然后檢查它,如下所示:
int x = 0;
x++;
if(x >= 10) {...}
但是,您將一元運算符放在表達式中,下表總結了它的用法。
+----------+-------------------+------------+-----------------------------------------------------------------------------------+
| Operator | Name | Expression | Description |
+----------+-------------------+------------+-----------------------------------------------------------------------------------+
| ++ | prefix increment | ++a | Increment "a" by 1, then use the new value of "a" in the residing expression. |
| ++ | postfix increment | a++ | Use the current value of "a" in the residing expression, then increment "a" by 1. |
| -- | prefix decrement | --b | Decrement "b" by 1, then use the new value of "b" in the residing expression. |
| -- | postfix decrement | b-- | Use the current value of "b" in the residing expression, then decrement "b" by 1. |
+----------+-------------------+------------+-----------------------------------------------------------------------------------+
public class UnaryOperators {
public static void main(String args[]) {
int n;
// postfix unary operators
n = 10;
System.out.println(n); // prints 10
System.out.println(n++); // prints 10, then increment by 1
System.out.println(n); // prints 11
n = 10;
System.out.println(n); // prints 10
System.out.println(n--); // prints 10, then decrement by 1
System.out.println(n); // prints 9
// prefix unary operators
n = 10;
System.out.println(n); // prints 10
System.out.println(++n); // increment by 1, then prints 11
System.out.println(n); // prints 11
n = 10;
System.out.println(n); // prints 10
System.out.println(--n); // decrement by 1, then prints 9
System.out.println(n); // prints 9
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.