Java: Difference between Conditional and Bitwise AND operator - & vs &&

There two AND operators in Java that we can use.

& - Bitwise AND operator
&& - Conditional AND operator.

In Java both above operators can be used in if conditions. However there is a difference how each works. Let's see with an example.

(x != 0) & (x > 1)  - With bitwise AND, it evaluates both (x !=0) and (x > 1) conditions. Then takes the AND of the two results.

(x != 0) && (x > 1)  - With conditional AND, it first valuates (x !=0) and only if it is true, (x > 1) condition will be evaluated. Then takes the AND of the two results. If (x!= 0) was false, it simply returns false.

What is the problem with using & in a condition?

There are cases where we can only execute a condition only some other condition is true.
See the example below.

(x != 0) & (3/x  > 1) - This will throw an exception if the x=0. So for such cases we can only use &&.

So in summary, it is always advisable to use conditional AND (&&) in if conditions. & should be used for bitwise operations with numbers. 


Popular posts from this blog

PHP-SOAP web service with out a WSDL

Boomi Mapping - Removing special chars from an input

How to add Maven dependency from a relative path referencing a local jar