Java: && (AND) and || (OR) in IF statements

Java: && (AND) and || (OR) in IF statements

其實這問題一直困擾著我,比說下面這段code,是否當VIDEO_LIST ==NULL時,第二個條件會不會被執行,若是會被執行,那.GET(Position)就會當機.是嗎?

if( VIDEO_LIST == null || VIDEO_LIST.get(position) == null || VIDEO_LIST.get(position).videoId == null )
{
   return;
}

來看看外國人怎麼說:

https://stackoverflow.com/questions/1795808/and-and-or-in-if-statements 

所以,外國人是說可以放心寫,因為第一個成立就不會執行第二個判斷.

用||可以,但注意用&&時就情況有所不同.
這觀念很重要,但有時別人問起, 我也說不出所以然...
|| 在判斷到Ture 時會Short circuit,後面不判斷.
&& 在判斷到false時會Short circuit,後面不判斷.

第二個人說了一個重點:
No, if a is true (in a or test), b will not be tested, as the result of the test will always be true, whatever is the value of the b expression.
Make a simple test:

will not throw a NullPointerException!

就是說||時,當第一個條件成立時,之後的就不會被判斷了.

---------------

第三個外國人說,這就叫做 Short circuit.

Short circuit here means that the second condition won't be evaluated.
If ( A && B ) will result in short circuit if A is False.
If ( A && B ) will not result in short Circuit if A is True.
If ( A || B ) will result in short circuit if A is True.
If ( A || B ) will not result in short circuit if A is False.

就是說
A && B : 若是 A == false, B就會被pass.
A || B : 若是 A == true, B就會被pass.

&&與|| 兩個運算子(Operator)在short circuit 成立條件不同,易混淆.
需特別注意.

ps: java是這樣,但其他語言不一定是這樣,需特別注意.ex: swift???

所謂short-circuit就是 stop evaluating once it knows the result.
這也會造成很多執行時的bug,
例如short-circuit成立時,你會不知道第二個條件是不是有寫對.
有時會在執行時才出錯.

最後來複習一下運算子 (Operator)優先順序:

結論:
if( json_filename == null || (json_filename != null && json_filename.trim().isEmpty()) )
{
   return false;
}

所以上面這樣寫是錯的,多餘判斷
只需:
if( json_filename == null ||  json_filename.trim().isEmpty())
{
   return false;
}

留言

這個網誌中的熱門文章

最爛的銀行服務-玉山銀行

Mark App Design Apps - Terms and Privacy Policy (服務條款,隱私權政策)

SMR疊瓦式hdd致命缺陷被解決????!!!

ios app 上架時app icon要注意事項

更改google drive預設存放目錄位置Change Google Drive Default Folder Location in Windows

舊有app在Android 12 閃退問題& app Splash screens

google play 正式發布前測試報告...非常好用.

app bundle and bundletool. 關於aab安裝問題

關於google play console app應用程式簽署

Google Play badge徽章產生器