Java Boolean Logical Operators

Introduction

The Boolean logical operators operate only on boolean operands.

Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
||Short-circuit OR
&&Short-circuit AND
! Logical unary NOT
&=AND assignment
|=OR assignment
^=XOR assignment
==Equal to
!=Not equal to
?:Ternary if-then-else

The following table shows the effect of each logical operation:

A B A | BA & B A ^ B!A
False False FalseFalse False True
TrueFalse True False TrueFalse
False True True False TrueTrue
TrueTrue True TrueFalse False

The following code operates on boolean logical values:

// Demonstrate the boolean logical operators.
public class Main {
  public static void main(String args[]) {
    boolean a = true;
    boolean b = false;
    boolean c = a | b;
    boolean d = a & b;
    boolean e = a ^ b;
    boolean f = (!a & b) | (a & !b);
    boolean g = !a;

    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&b|a&!b = " + f);
    System.out.println("       !a = " + g);
  }//w  ww.j  a  v  a2s .  c  o m
}



PreviousNext

Related