&與&&都是邏輯與
不同的是&左右兩邊的判斷都要進行,而&&是短路與,當&&左邊條件為假則不用再判斷右邊條件,所以效率更高
例如,對于if(str != null && !str.equals(“”))表達式,當str為null時,后面的表達式不會執行,所以不會出現NullPointerException如果將&&改為&,則會拋出NullPointerException異常。If(x==33 & ++y>0) y會增長,If(x==33 && ++y>0)不會增長
&還可以用作位運算符,當&操作符兩邊的表達式不是boolean類型時,&表示按位與操作,我們通常使用0x0f來與一個整數進行&運算,來獲取該整數的最低4個bit位,例如,0x31 & 0x0f的結果為0x01。
package com.swift;public class And_Test {public static void main(String[] args) {/** & 和 &&*/String str=null;if(str != null & !str.equals("")) {System.out.println("有異常了,因為str沒有開辟空間");}}}
按位與
package com.swift;public class And_Test {public static void main(String[] args) {/** & 和 &&*/String str=null;if(str != null && !str.equals("")) {System.out.println("有異常?");}System.out.println(Integer.toHexString(0x3a + 0x45));System.out.println(Integer.toHexString(0x31 & 0x0f));}}
?