Logical Operators in Java:
Logical operators are used to perform logical operations, usually on boolean values. These operators return either true or false and are most commonly used in conditions like if, while, and for.
List of Logical Operators:
| Operator | Name | Description | Example | Result |
|---|---|---|---|---|
| && | Logical AND | Returns true only if both conditions are true | a > 5 && a < 10 | true if both are true |
| || | Logical OR | Returns true if any one conditions is true | a== || b==0 | True if any one true |
| ! | Logical NOT | Reverses the boolean value | !(a == b) | true if false |
Short-Circuit Behavior:
- && (AND):
- If the first condition is false, Java skips checking the second one (because result is already false).
- || (OR):
- If the first condition is true, Java skips the second one (because result is already true).
This is known as short-circuit evaluation and helps improve performance.
Example:
class ShikshaSanchar {
public static void main(String[] args) {
// Logical AND (&&)
int age = 20;
boolean hasID = true;
if (age >= 18 && hasID) {
System.out.println("You are eligible to vote.");
}
// Logical OR (||)
boolean hasEmail = false;
boolean hasPhone = true;
if (hasEmail || hasPhone) {
System.out.println("You can recover your account.");
}
// Logical NOT (!)
boolean isLoggedIn = false;
if (!isLoggedIn) {
System.out.println("Please log in to continue.");
}
// Logical AND in loop
System.out.println("Printing numbers divisible by 3 and less than 10:");
for (int i = 1; i <= 15; i++) {
if (i % 3 == 0 && i < 10) {
System.out.println(i);
}
}
}
}
Output:
You are eligible to vote.
You can recover your account.
Please log in to continue.
Printing numbers divisible by 3 and less than 10:
3
6
9
Explanation:
- age >= 18 && hasID → Checks both conditions to allow voting.
- hasEmail || hasPhone → If either is true, account recovery is possible.
- !isLoggedIn → Reverses false to true → Prompts for login.
- Loop: i % 3 == 0 && i < 10 → Finds numbers divisible by 3 and < 10.
Notes:
- Logical operators are essential in decision making.
- Can be combined with relational operators (>, <, ==, etc.).
- Often used in if, while, for, and complex conditions.