package Feb2017;
public class Ques0214 {
public static void main(String[] args) {
boolean b1 = true;
if (b1 == true || method(true)) {
System.out.println("location01");
}
}
public static boolean method(boolean location) {
if (location == true) {
System.out.println("location02");
}
System.out.println("location03");
return true;
}
}
主程序輸出結果?
location01
b1 == true 為 true。|| 為短路邏輯或:左邊為 true 時,不再計算右邊表達式。method(true) 完全不會被調用,因此無任何輸出。if 塊,打印 location01。
if (b1 == true | method(true)) // 會調用 method,輸出 location02, location03, location01
&&、||:短路邏輯運算符,提升性能,可用於空指針保護(如 obj != null && obj.method())。&、|:邏輯運算符(非短路),兩邊必執行。&、| 同時也是位運算符(操作數為整數時)。