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

前端 未结 4 1843
谎友^
谎友^ 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.

提交回复
热议问题