class Logic{ ??? public ststic void main(String[] args){ ??????? int a=1; ??????? int b=1; ??????? if(a<b && b<a/0){ ??????????? System.out.println("Oh,That's Impossible!!!"); ??????? }else{ ??????????? System.out.println("That's in my control."); ??????? } ??? } } |
??? “&&”運算符檢查第一個表達式是否返回“false”,如果是“false”則結果必為“false”,不再檢查其他內容。
“a/0”是個明顯的錯誤!但短路運算“&&”先判斷“a<b”,返回“false”,遂造成短路,也就不進行“a/0”操作了,程序會打出"That's in my control."。這個時候,交換一下“&&”左右兩邊的表達式,程序立即拋出異?!癹ava.lang.ArithmeticException: / by zero”。
class Logic{ |
??? “||”運算符檢查第一個表達式是否返回“true”,如果是“true”則結果必為“true”,不再檢查其他內容。
“a/0”是個明顯的錯誤!但短路運算“||”先執行“a==b”判斷,返回“true”,遂造成短路,也就不進行“a/0”操作了,程序會打出"That's in my control."。這個時候,交換一下“||”左右兩邊的表達式,程序立即拋出異常“java.lang.ArithmeticException: / by zero”。
非短路運算符包括 “& 與”、“| 或”、“^ 異或”,一般稱為“邏輯操作”
class Logic{ |
??? “&”運算符不會造成短路,它會認認真真的檢查每一個表達式,雖然“a<b”已經返回“flase”了,它還是會繼續檢查其他內容,以至于最終拋出異?!癹ava.lang.ArithmeticException: / by zero”。
????
class Logic{ ??? public ststic void main(String[] args){ ??????? int a=1; ??????? int b=1; ??????? if(a==b?| b<a/0){ ??????????? System.out.println("That's in my control."); ??????? }else{ ??????????? System.out.println("Oh,That's Impossible!!!"); ??????? } ??? } } |
??? 同理,“|”運算符也不會造成短路,雖然“a==b”已經返回“true”了,它還是會繼續檢查其他內容,以至于最終拋出異?!癹ava.lang.ArithmeticException: / by zero”。
??? “^”運算符道理是一樣的,就不在這里羅索了。
??? 最后。短路運算符只能用于邏輯表達式內,非短路運算符可用于位表達式和邏輯表達式內。也可以說:短路運算只能操作布爾型的,而非短路運算不僅可以操作布爾型,而且可以操作數值型。
請注意!引用、轉貼本文應注明原作者:Rosen Jiang 以及出處:http://www.aygfsteel.com/rosen