Java - Logical Operators

Java

In this tutorial we will learn about logical operators in Java programming language.

We use the logical operators to test more than one condition. Logical expressions yields either true or false boolean value.

There are three logical operators in Java.

OperatorDescription
&&Logical AND
||Logical OR
!Logical NOT

Click here if you are interested in exploring Boolean Algebra.

Logical AND

The logical AND && operator will give true value if both the operands are true. Otherwise, it will give false.

Truth table of logical AND operator.

ABA && B
falsefalsefalse
falsetruefalse
truefalsefalse
truetruetrue

In the following example we will get true only if both expressions evaluates to true.

class Logical {
  public static void main(String args[]) {
    int a = 10;
    int b = 20;
    int x = 40;
    int y = 50;
    
    boolean m = a < b;    // this will give true
    boolean n = y > x;    // this will give true
    
    System.out.println("Result: " + (m && n) );
  }
}

Since, both m and n are true so, we get true.

Output:

Result: true

Logical OR

The logical OR || operator will give true value if any one of the operand is true. If both are false then it will return false.

Truth table of logical OR operator.

ABA || B
falsefalsefalse
falsetruetrue
truefalsetrue
truetruetrue

In the following example we will get true if any one of the expression evaluates to true.

class Logical {
  public static void main(String args[]) {
    int a = 10;
    int b = 20;
    int x = 40;
    int y = 50;
    
    boolean m = a < b;    // this will give true
    boolean n = x > y;    // this will give false
    
    System.out.println("Result: " + (m || n) );
  }
}

Since, one of the expression i.e., m is true so, we get true.

Output:

Result: true

Logical NOT

The logical NOT ! operator will give true value if the operand is false. And it will return false value if the operand is true.

Logical NOT operator works with only one operand.

Truth table of logical NOT operator.

A!A
falsetrue
truefalse

In the following example we will get true only if the expression evaluates to false.

class Logical {
  public static void main(String args[]) {
    int a = 10;
    int b = 20;
    
    boolean m = a > b;    // this will give false
    
    System.out.println("Result: " + (!m) );
  }
}

Since, m is false so, we get true.

Output:

Result: true