2017-04-15 33 views
0

(我真的不知道該怎麼表達出該問題的任何好。我敢肯定有這裏涉及到一個概念,我不知道,所以請您能否提供一個更好的措辭 - 或直接我一個一個回答問題,如果這原來是一式兩份)爲什麼一個print語句不執行方法時從所謂的「空」主

我一直在玩弄在Java中,發現了一些問題,我無法解釋。在下面的代碼中,我期望打印0。但是,沒有打印。我可以想到的唯一可能的解釋是主要方法在printstream被刷新之前結束,但它對我來說可能沒有意義。總之,怎麼了這段代碼打印什麼,而不是0

class Test { 
    public static void main (String [] args) { 

     if(false && method()){ 

     } 
    } 
    public static boolean method(){ 
     System.out.println(0); 
     return true; 
    } 
} 

回答

1

因爲該方法沒有被調用。 false導致和short-ciruit

if(false & method()){ // <-- body will not execute, but the evaluation 
         //  does not short circuit. 

if(false || method()){ // <-- body will execute, method() is true 

if(method() && false){ // <-- body will not execute, because of false. 

如你預期會工作。

+0

啊就是這麼簡單......爲什麼會第一個例子'假method'有什麼不同?因爲它是按位?它仍然會總是導致的論點是錯誤的 – marcman

+0

因爲它是[渴望](https://en.wikipedia.org/wiki/Eager_evaluation),第二短路。他們是不同的運營商。 –

+0

噢,好的,謝謝你的解釋 – marcman

相關問題