为什么&=运算符与&&的工作方式不同

Egi*_*gis -1 java boolean operators

我只是好奇java是如何工作的.有人可以解释为什么getBoolean在案例1中调用而未在案例2中调用?

public class Main {

    public static void main(String[] args) {
        System.out.println("---------- Case 1 ----------");
        boolean b = false;
        b &= getBoolean(true);

        System.out.println("---------- Case 2 ----------");
        b = false;
        b = b && getBoolean(true);
    }

    private static boolean getBoolean(boolean bool) {
        System.out.println("getBoolean(" + bool + ") was called\n");
        return bool;
    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

---------- Case 1 ----------
getBoolean(true) was called

---------- Case 2 ----------
Run Code Online (Sandbox Code Playgroud)

Sty*_*tyl 5

b &= a是一个快捷方式b = b & ab = b && a

这是因为之间的差异&&&运营商.

  • &操作的结果总是条件两侧.

  • &&只有在需要时,操作员才会评估秒.

所以,getBoolean(true)不会在第二种情况下运行.