Operators

Java Program to Demonstrate Logical Operators

A Java program to demonstrate the usage of logical operators.

Problem Description

Write a Java program to demonstrate the usage of logical operators: AND (&&), OR (||), and NOT (!).

Code

LogicalOperators.java
public class LogicalOperators {
    public static void main(String[] args) {
        boolean a = true;
        boolean b = false;

        System.out.println("a && b: " + (a && b));
        System.out.println("a || b: " + (a || b));
        System.out.println("!a: " + (!a));
        System.out.println("!b: " + (!b));
    }
}

Output

a && b: false
a || b: true
!a: false
!b: true

Explanation

  1. && (Logical AND): Returns true if both operands are true.
  2. || (Logical OR): Returns true if at least one operand is true.
  3. ! (Logical NOT): Reverses the boolean value of the operand.

Try Yourself

  1. Combine Operators: Evaluate (5 > 3) && (8 > 5). Is it true or false?
  2. Short Circuit: In false && (5 / 0 == 0), does the division by zero cause an error? Why or why not?
  3. De Morgan's Laws: Is !(A && B) the same as !A || !B? Write a code to verify.
  4. Three Conditions: Check if a number n is between 10 and 20 (inclusive). Hint: n >= 10 && n <= 20
  5. Brain Twister: What is the result of true || false && false? (Check operator precedence).