Java Logical Operators

Description

The Boolean logical operators operate on boolean operands.

Logical Operator List

The following table lists all Java boolean logical operators.

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

True table

The following table shows the effect of each logical operation:

A B A | B A & BA ^ B!A
FalseFalseFalseFalse FalseTrue
True FalseTrue False True False
FalseTrue True False True True
True True True True FalseFalse

Example

The following program demonstrates 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);
//from ww w .ja  v  a 2s.c om
  }
}
]]>

The output:

Example 2

The following program demonstrates the bitwise logical operators:

 
public class Main {
  public static void main(String args[]) {
    int a = 1;/*from  w w w . j a  va2s .c  o  m*/
    int b = 2;
    int c = a | b;
    int d = a & b;
    int e = a ^ b;
    int f = (~a & b) | (a & ~b);
    int g = ~a & 0x0f;

    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);

  }
}

Here is the output from this program:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures