Java Logical Operators

In this chapter you will learn:

  1. What are Java Boolean Logical Operators
  2. Logical Operator List
  3. True table
  4. Example - boolean logical operators
  5. How to use the Bitwise 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);
/* w w  w.j a va  2 s.com*/
  }
}
]]>

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 v a2s  .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:

Next chapter...

What you will learn in the next chapter:

  1. What is Java Logical Operators Shortcut
  2. Example - Short-Circuit Logical Operators in Java
  3. Example - Not Shortcut Logical Operators
Home »
  Java Tutorial »
    Java Langauge »
      Java Operator
Java Arithmetic Operators
Java Compound Assignment Operators
Java Increment and Decrement Operator
Java Logical Operators
Java Logical Operators Shortcut
Java Relational Operators
Java Bitwise Operators
Java Left Shift Operator
Java Right Shift Operator
Java Unsigned Right Shift
Java ternary operator