How does Java deal with multiple conditions inside a single IF statement

前端 未结 4 1831
谎友^
谎友^ 2020-12-15 21:40

Lets say I have this:

if(bool1 && bool2 && bool3) {
...
}

Now. Is Java smart enough to skip checking bool2 and bool2 if boo

相关标签:
4条回答
  • 2020-12-15 22:12

    Please look up the difference between & and && in Java (the same applies to | and ||).

    & and | are just logical operators, while && and || are conditional logical operators, which in your example means that

    if(bool1 && bool2 && bool3) {
    

    will skip bool2 and bool3 if bool1 is false, and

    if(bool1 & bool2 & bool3) {
    

    will evaluate all conditions regardless of their values.

    For example, given:

    boolean foo() {
        System.out.println("foo");
        return true;
    }
    

    if(foo() | foo()) will print foo twice, and if(foo() || foo()) - just once.

    0 讨论(0)
  • 2020-12-15 22:20

    Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.

    This means that the following code is completely safe:

    if(p != null && p.getAge() > 10)
    

    Also, a || b never evaluates b if a evaluates to true.

    0 讨论(0)
  • 2020-12-15 22:20

    Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

    Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

    if(s != null && s.length() > 0)
    

    or

    if(s == null || s.length() == 0)
    

    BTW if you use & and | it will always evaluate both sides of the expression.

    0 讨论(0)
  • 2020-12-15 22:36

    Yes,that is called short-circuiting.

    Please take a look at this wikipedia page on short-circuiting

    0 讨论(0)
提交回复
热议问题