Logical Operators in Java
Introduction
Logical operators in Java are used to perform logical operations on boolean values. They help in decision-making expressions and are often combined with relational operators. The result of a logical operation is always true or false.
Logical Operators in Java
Java provides three primary logical operators:
Logical AND (&&) Operator :
- The AND (
&&) operator returnstrueonly if both conditions aretrue.
- If the first condition is
false, the second condition is not evaluated.
Truth Table for AND (&&):
Example 1: AND Operator:
class Main {
public static void main(String[] args) {
System.out.println((2 < 3) && (1 < 2)); // true
}
}
Explanation:
(2 < 3) && (1 < 2)
true && true → true
Example 2: AND Operator with a False Condition :
class Main {
public static void main(String[] args) {
System.out.println((10 < 5) && (6 < 9)); // false
}
}
Explanation:
(10 < 5) && (6 < 9)
- false && (6 < 9)
- Since the first condition is
false, Java does not check the second condition.
Logical OR (||) Operator :
-
The OR (
||) operator returns true if at least one condition is true.
- If the first condition is
true, the second condition is not checked.
class Main {
public static void main(String[] args) {
System.out.println((12 > 13) || (15 < 12)); // false
}
}
Explanation:
(12 > 13) || (15 < 12)
false || false → false
Example 2: OR Operator with a True Condition :
class Main {
public static void main(String[] args) {
System.out.println((2 < 3) || (2 < 1)); // true
}
}
Explanation:
(2 < 3) || (2 < 1)
true || (2 < 1)
Since the first condition is true, Java does not check the second condition.
Logical NOT (!) Operator:
- The NOT (
!) operator is a unary operator that inverts the boolean value.
- If a condition is
true, applying ! makes it false, and vice versa.
class Main {
public static void main(String[] args) {
System.out.println(!(5 > 7)); // true
}
}
Explanation:
!(5 > 7) → !(false) → true
Example 2: NOT Operator with a True Condition :
class Main {
public static void main(String[] args) {
System.out.println(!(2 < 3)); // false
}
}
Explanation:
!(2 < 3) → !(true) → false
Summary
- Logical AND (
&&) returns true only if both conditions are true.
- Logical OR (
||) returns true if at least one condition is true.
- Logical NOT (
!) reverses the boolean value.
.png)
