"var & = expr" does not behave like "var = var && expr"

I'm just curious. I would like to know if there is a specific reason why the expression

var &= expr 

doesn't behave the same way

 var = var && expr. 

It looks like the expression in the first is executed regardless of the false value in var.

I am using Java 6, FYI. This code:

 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"); } } 

Gives me:

 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) 
+4
source share
6 answers

& does not behave like && 1,2

& is looking bitwise / boolean.

&& is short-circuiting logical-And.


1 A string with &= equivalent to test = test & (string.length() > 0) , which will also fail.

2 See Why We Usually Use` || `not` | `what is the difference? - The answers also cover the use of && and & .

+10
source

It looks like the expression in the first is executed regardless of the false value in var.

This is because the second expression uses a short circuit estimate, but the first expression does not.

+3
source

They do not match, since & is a bitwise operator, and && is a logical operator in a boolean.

var &= expr equivalent to var = var & expr , not var = var && expr .

+2
source

In your case

 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 
0
source

& bitwise AND

&& is a logical I.

true && true = true ..

& works with numbers, && works with boolean expressions.

0xFE & 0xFF results in 0xFE .

-1
source
 var &= expr 

equivalently

 var = var & expr 

In other words, it performs bitwise or

 var = var && expr 

does boolean or var and expr

-1
source

All Articles