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 && bevaluates tofalsebecausebisfalse.- 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 || bevaluates totruebecauseaistrue.- Logical OR is used when any one condition being true is sufficient.
3. Logical NOT (!)
Definition:
The NOT operator inverts the boolean value:
truebecomesfalsefalsebecomestrue
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:
!areturnsfalsebecauseaistrue.- Logical NOT is useful for reversing conditions in control statements.
Summary Table
| Operator | Symbol | Returns 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.