public class Demo {
public static void main(String args[]) {
boolean flag = 10%2 == 1 && 10 / 3 == 0 && 1 / 0 == 0 ;
System.out.println(flag ? "mldn" : "yootk") ;
}
}
代碼如上,我任務(wù)考察的是 && 符號(hào) 與 & 符號(hào)的區(qū)別,但是在最后一個(gè) 1 / 0 == 0 這個(gè)竟然能走通,而且打印出來了yootk,這個(gè)除數(shù)不是不能為零的嗎?為什么能走通呢?很是費(fèi)解,希望大神可以給解釋下,謝謝。
&& and || have a short-circuit effect:
The root cause of the short-circuit effect is to improve performance
&& operator checks whether the first expression returns false. If it is false, the result must be false and no other content is checked.
|| operator checks whether the first expression returns true. If it is true, the result Must be true, no other content will be checked
public static void main(String args[]) {
boolean flag = 10%2 == 1 && 10 / 3 == 0 && 1 / 0 == 0 ;
System.out.println(flag ? "mldn" : "yootk") ;
}
10%2 == 1 is false, the following content will no longer be executed
10%2 == 1 is false, the final result of the entire expression is false, and the following will not be executed, which is a short circuit.
&&
and ||
will short-circuit, but &
and |
will not. If you change &&
to &
, something will definitely happen.