BOOLEAN LOGICAL
OPERATOR
The Boolean logical operator operates only on boolean operands. All of the binary
logical operators combine two boolean values to form a resultant boolean value.
Operator Meaning
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
&& Short-circuit AND
|| Short-circuit OR
! Logical NOT
The truth table for few operations:
A B A|B A&B A^B !A
False False False False False True
False True True False True True
True False True False True True
True True True True False False
Demonstration of Boolean Logical operators
class BoolLogic
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
System.out.println(" a = " + a);
System.out.println("b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println(" !a = " + g);
}
}
output :a = true
b = false
a|b = true
a&b = false
a^b = true
!a&b|a&!b = true
!a = false
Short-Circuit Logical Operators
The short-circuit AND (&&) and OR (||) operators will not evaluate the second
operand if the first is decisive.
int x=0, n=5;
……..
if(x!=0 && n/x > 0)
//do something
Here, the first operand x!= 0 is false. If we use logical AND (&) then the second
operand n/x>0 will be evaluated and we will get DivisionByZero Exception. So, to
avoid this problem we use && operator which will never evaluated second operand
if the first operand results into false.