What is the difference between & and && in Java?

Lavneesh picture Lavneesh · Apr 6, 2011 · Viewed 179.8k times · Source

I always thought that && operator in Java is used for verifying whether both its boolean operands are true, and the & operator is used to do Bit-wise operations on two integer types.

Recently I came to know that & operator can also be used verify whether both its boolean operands are true, the only difference being that it checks the RHS operand even if the LHS operand is false.

Is the & operator in Java internally overloaded? Or is there some other concept behind this?

Answer

ITroubs picture ITroubs · Apr 6, 2011

& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false

(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.

(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).

EDIT:

exprA | exprB <-- this means evaluate exprA then evaluate exprB then do the |.

exprA || exprB <-- this means evaluate exprA and only if this is false then evaluate exprB and do the ||.