Logical AND, OR, NOT Operators in Java

Introduction

Logical operators in Java are used to combine multiple boolean expressions or invert a boolean value. They are commonly used in conditional statements like if, while, and for loops to control the program flow. Java supports three main logical operators: AND (&&), OR (||), and NOT (!).


1. Logical AND (&&)

Definition:
The AND operator returns true only if both operands are true. Otherwise, it returns false.

Example Code:

public class LogicalAND {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
if (a && b) {
System.out.println("Both are true");
} else {
System.out.println("At least one is false");
}
}
}

Explanation:

  • a && b evaluates to false because b is false.
  • Logical AND is used when all conditions must be true for the block to execute.

2. Logical OR (||)

Definition:
The OR operator returns true if at least one operand is true. It returns false only if both operands are false.

Example Code:

public class LogicalOR {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
if (a || b) {
System.out.println("At least one is true");
} else {
System.out.println("Both are false");
}
}
}

Explanation:

  • a || b evaluates to true because a is true.
  • Logical OR is used when any one condition being true is sufficient.

3. Logical NOT (!)

Definition:
The NOT operator inverts the boolean value:

  • true becomes false
  • false becomes true

Example Code:

public class LogicalNOT {
public static void main(String[] args) {
boolean a = true;
System.out.println("Original value: " + a);
System.out.println("Inverted value: " + !a);
}
}

Explanation:

  • !a returns false because a is true.
  • Logical NOT is useful for reversing conditions in control statements.

Summary Table

OperatorSymbolReturns true when
AND&&Both operands are true
OR`
NOT!Operand is false (inverts the value)

Conclusion

Logical operators are fundamental in Java for decision-making and controlling program flow.

  • AND (&&) ensures all conditions are true.
  • OR (||) allows execution if any condition is true.
  • NOT (!) inverts a boolean expression.

Using these operators effectively allows you to write complex conditional logic in your Java programs.


Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper