What is wrong with the short circuit logic in this Java code?

后端 未结 9 1167
挽巷
挽巷 2021-01-18 01:58

Why doesn\'t func3 get executed in the program below? After func1, func2 doesn\'t need to get evaluated but for func3, shouldn\'t it?

if (func1() || func2()          


        
9条回答
  •  感动是毒
    2021-01-18 02:33

    Java uses Lazy evaluation.

    Since Func1 always returns true, the entire expression MUST be true, so it shortcuts the rest of the expression.

    true || (???)
    

    and

    false && (???)
    

    will always shortcut.

    To turn off shortcut evaluation, use | and & instead of || and &&

    We can use this to good effect:

    String s;
    if (s != null && !s.equals("")) ...
    

    Meaning that if s is null, we won't even have to try to call s.equals, and we won't end up throwing an NullPointerException

提交回复
热议问题