"var&= expr"的行为不像"var = var && expr"

Béa*_*tat 4 java compilation

我只是好奇.我想知道表达式是否有特定原因

var &= expr
Run Code Online (Sandbox Code Playgroud)

表现不一样

var = var && expr.
Run Code Online (Sandbox Code Playgroud)

看起来第一个中的表达式正在执行,而不管var上的错误值.

我正在使用Java 6,FYI.这段代码:

public class Test
{
    protected static String getString()
    {
        return null;
    }

    public static void main(String... args)
    {
        String string = getString();
        boolean test = (string != null);
        test = test && (string.length() > 0);
        System.out.println("First test passed");
        test &= (string.length() > 0);
        System.out.println("Second test passed");
    }
}
Run Code Online (Sandbox Code Playgroud)

给我:

First test passed
Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Run Code Online (Sandbox Code Playgroud)

小智 10

&不像&&1,2

&是一个渴望的按位/布尔 - 和.

&&是一个短路的逻辑 - 和.


1线路&=相当于test = test & (string.length() > 0),也会失败.

2看看为什么我们通常使用`||`而不是`|`,有什么区别?- 答案还包括使用&&&.