Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

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?

1 Answer

0 votes
by (46k points)
& <-- 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).

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 ||.

Related questions

0 votes
1 answer
asked Jul 30, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 28, 2019 in Java by Anvi (10.2k points)

Browse Categories

...