2013-03-08 60 views
4

我只是好奇。我想知道是否有一個具體原因 「var&= expr」的行爲不像「var = var && expr」

不行爲的方式

var = var && expr. 

看起來好像是第一個表達同樣被不管執行的表達

var &= expr 
對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"); 
    } 
} 

給我:

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) 
+1

Ref。 http://stackoverflow.com/questions/7101992/why-do-we-usually-use-not-what-is-the-difference,http://stackoverflow.com/questions/9264897/reason-for-the- exsistance-的,非短路邏輯運算符,http://stackoverflow.com/questions/4014535/vs-and-vs – 2013-03-08 22:48:46

回答

2

他們是不一樣的,因爲&是位運算符和&&是針對布爾邏輯運算符。

var &= expr相當於var = var & expr而不是var = var && expr

3

它看起來像第一個表達式正在執行,無論var上的值是否爲假。

這是因爲第二個表達式使用短路評估,而第一個表達式不使用短路評估。

-1

&是按位與

&&是邏輯AND。

true && true = true ..

&作品上的數字,&&作品的布爾表達式。

0xFE & 0xFF結果在0xFE

+0

和工作在布爾太 – MrBackend 2014-02-26 18:59:50

-1
var &= expr 

相當於

var = var & expr 

換句話說,它做了按位

var = var && expr 

做邏輯或VAR和EXPR

+0

雖然答案是正確的,你還在懷念的點短路。與布爾運算符合得很好。 – MrBackend 2014-02-26 19:01:11

0

你的情況

test = test && (string.length() > 0); // test = false that why strings.length not evaluated 

test &= (string.length() > 0); //calling length on null object that why NPE