java中“&&”和“||”短路詳解

原文鏈接:https://blog.csdn.net/qq_38442065/article/details/81007041

短路運算符就是我們常用的“&&”、“||”,一般稱爲“條件操作”。


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."。這個時候,交換一下“&&”左右兩邊的表達式,程序立即拋出異常“java.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!!!");

        }

    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章