While the basic difference is that &
is used for bitwise operations mostly on long
, int
or byte
where it can be used for kind of a mask, the results can differ even if you use it instead of logical &&
.
The difference is more noticeable in some scenarios:
First point is quite straightforward, it causes no bugs, but it takes more time. If you have several different checks in one conditional statements, put those that are either cheaper or more likely to fail to the left.
For second point, see this example:
if ((a != null) & (a.isEmpty()))
This fails for null
, as evaluating the second expression produces a NullPointerException
. Logical operator &&
is lazy, if left operand is false, the result is false no matter what right operand is.
Example for the third point -- let's say we have an app that uses DB without any triggers or cascades. Before we remove a Building object, we must change a Department object's building to another one. Let's also say the operation status is returned as a boolean (true = success). Then:
if (departmentDao.update(department, newBuilding) & buildingDao.remove(building))
This evaluates both expressions and thus performs building removal even if the department update failed for some reason. With &&
, it works as intended and it stops after first failure.
As for a || b
, it is equivalent of !(!a && !b)
, it stops if a
is true, no more explanation needed.