Logical Operators
Logical operators in Java are used to combine multiple conditions and produce a boolean result (true or false). They are fundamental for decision-making, validations, and control flow in real-world Java programs.
This topic is very common in interviews and heavily used in if statements, loops, and business rules.
What Are Logical Operators?
- Operate on boolean expressions
- Combine two or more conditions
- Return a boolean result
List of Logical Operators in Java
| Operator | Name | Description |
|---|---|---|
| && | Logical AND | True if both conditions are true |
| || | Logical OR | True if at least one condition is true |
| ! | Logical NOT | Reverses the boolean value |
1. Logical AND (&&)
Returns true only if both conditions are true.
int age = 25;
boolean hasId = true;
if (age >= 18 && hasId) {
System.out.println("Entry allowed");
}
Short-Circuit Behavior (&&)
int a = 10;
int b = 0;
if (b != 0 && a / b > 2) {
System.out.println("Safe division");
}
Why it matters: Second condition is not evaluated if the first is false, preventing exceptions.
2. Logical OR (||)
Returns true if at least one condition is true.
boolean isAdmin = false;
boolean isManager = true;
if (isAdmin || isManager) {
System.out.println("Access granted");
}
Short-Circuit Behavior (||)
int x = 5;
if (x > 0 || x / 0 > 1) {
System.out.println("No exception");
}
Why it matters: Second condition is skipped if first is true.
3. Logical NOT (!)
Reverses the boolean value.
boolean isActive = false;
if (!isActive) {
System.out.println("User is inactive");
}
Logical Operators Truth Table
| Condition A | Condition B | A && B | A || B |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
Logical Operators vs Bitwise Operators (Interview Trap)
| Operator | Type | Behavior |
|---|---|---|
| && | Logical | Short-circuit |
| || | Logical | Short-circuit |
| & | Bitwise / Boolean | No short-circuit |
| | | Bitwise / Boolean | No short-circuit |
Example Difference
int a = 10;
int b = 0;
if (b != 0 & a / b > 1) {
// ❌ ArithmeticException
}
Common Use Cases
- Input validation
- Authorization checks
- Business rule conditions
- Loop termination logic
Common Beginner Mistakes
- Confusing && with &
- Confusing || with |
- Forgetting short-circuit behavior
- Overusing complex conditions
- Ignoring operator precedence
Interview-Ready Answers
Short Answer
Logical operators are used to combine boolean expressions and return a boolean result.
Detailed Answer
Java logical operators (&&, ||, !) are used to evaluate multiple conditions in decision-making statements. Logical AND and OR support short-circuit evaluation, improving performance and preventing runtime errors.
Key Takeaway
Logical operators are the backbone of decision-making logic in Java. Understanding short-circuit behavior is essential for writing safe and efficient code.