一句話區分運算符 |
和 ||
,&
和 &&
太長不看版:
結果上沒有區別,運算過程中
&
兩邊都算,而&&
先算左側,若左側爲 false 那麼右側就不運算了。
如何區分運算符 |
和 ||
,&
和 &&
?
首先,我們知道 |
和 &
定義爲位運算符,||
和 &&
定義爲邏輯運算符。
在區分之前,我們先要知道 |
與 &
的含義:
&
按位與操作,按二進制位進行"與"運算。運算規則:(有 0 則爲 0)|
按位或運算符,按二進制位進行"或"運算。運算規則:(有 1 則爲 1)
|
是按位或:先判斷條件1,不管條件1是否可以決定結果(這裏決定結果爲true),都會執行條件2
||
是邏輯或:先判斷條件1,如果條件1可以決定結果(這裏決定結果爲true),那麼就不會執行條件2
1.按位與(&)和按位或(|):
標準的按位與(&)和按位或(|),不論第一個表達式爲true or false,都計算第二個表達式。
例如:
if (c==0 | e++ < 100) { d=12;} //不論c是否等於0,e都被自增量。
if (c==0 | e++ < 100) { d=12;} //不論c是否等於0,e都被自增量。
2.邏輯與(&&)和邏輯或(||)
A&&B, 當A爲false時,不去計算B的值而直接返回false;當A爲true時,計算B的值。
A || B,當A爲true時, 不去計算B的值而直接返回true;當A爲false時,計算B的值。
3.應用比較
短路&& 是很有用的。例如,下面的程序語句說明了短路邏輯運算符的優點,用它來防止被0除的錯誤:
if (denom != 0 && num / denom > 10)
既然用了邏輯與(&&)運算符,就不會有當denom爲0時產生的意外運行時錯誤。如果該行代碼使用標準與運算符(&),它將對兩個運算數都求值,當出現被0除的情況時,就會產生運行時錯誤。
例題
Given the following code:
public class Test {
private static int j = 0;
private static Boolean methodB(int k) {
j += k;
return true;
}
public static void methodA(int i) {
boolean b;
b = i < 10 | methodB(4);
b = i < 10 || methodB(8);
}
public static void main(String args[]) {
methodA(0);
System.out.println(j);
}
}
What is the result?
A. The program prints”0”
B. The program prints”4”
C. The program prints”8”
D. The program prints”12”
E. The code does not complete.
答案
B
解析
在main函數中先調用methodA(0)
在methodA中,第二行
b = i < 10 | methodB(4);
//中間爲與計算符,執行完methodB(4)後,j = 4
methodA中,第三行
b = i < 10 || methodB(8);
//中間爲或計算符,因爲i < 10 已成立,不需要後續計算
所以最後結果輸出爲4