Logical operators in Java are boolean operators used to combine multiple conditions in decision-making and looping constructs. They allow you to evaluate multiple boolean expressions and determine the flow of execution based on the overall result.
Here’s simple example of using logical operators in Java in which we have used the OR (||
) operator to combine two boolean expressions:
public class LogicalOrExample {
public static void main(String[] args) {
boolean isWeekend = true;
boolean isHoliday = false;
// Check if it is a weekend or a holiday.
if (isWeekend || isHoliday) {
System.out.println("You can relax today!");
} else {
System.out.println("It's a working day.");
}
}
}
Output:
You can relax today!
In this example, we have used || operator that checks if at least one condition is true. Since isWeekend is true, so the whole expression becomes true. Therefore, “You can relax today!” is printed on the console.
Table of Contents
Types of Logical Operators in Java
Java mainly provides three logical operators which are as follows:
Operator | Description | Symbol |
---|---|---|
AND | Returns true if both operands are true. | & |
OR | Returns true if at least one operand is true. | || |
NOT | Inverts the boolean value. | ! |
Logical AND (&)
The logical AND operator (&) is used to combine two or more conditions. This operator returns true only if all the conditions are true. If any one condition is false, the result will be false. The general syntax to use the logical AND operator is as:
condition1 & condition2
Example 1: Using Logical AND Operator
public class LogicalAndExample {
public static void main(String[] args) {
int age = 25;
boolean hasDrivingLicense = true;
// Check if the person is older than 18 AND has a driving license.
if (age > 18 & hasDrivingLicense) {
System.out.println("You are eligible to drive.");
} else {
System.out.println("You are not eligible to drive.");
}
}
}
Output:
You are eligible to drive.
In the example, the first condition age > 18 is true because 25 is greater than 18. The second condition hasDrivingLicense is also true. Since both conditions are true, the entire condition (age > 18 & hasDrivingLicense) is true. So, the message “You are eligible to drive.” is displayed on the console.
Real-World Use Case of Logical AND Operator
Logical AND is commonly used in the following scenarios:
- Form validations (e.g., email is valid and password is strong)
- Permission checks (e.g., user is admin and account is active)
- Business rules (e.g., product is in stock and payment is successful)
Logical OR (||
) Operator in Java
The Logical OR (||) operator is used to combine two or more boolean expressions. This operator returns true if at least one of the conditions is true. If all conditions are false, then it returns false. The generl syntax to use logical OR operator is as:
condition1 || condition2
Example 2: Using Logical OR Operator
public class LogicalOrExample {
public static void main(String[] args) {
boolean isWeekend = false;
boolean isHoliday = true;
// Check if today is a weekend OR a holiday.
if (isWeekend || isHoliday) {
System.out.println("You can relax today!");
} else {
System.out.println("It's a working day. Get to work!");
}
}
}
Output:
You can relax today!
In this example, the first condition isWeekend = false and the second condition isHoliday = true. Since one of the conditions is true, the OR condition evaluates to true. Therefore, the program prints: “You can relax today!”.
Real-Time Use Cases of Logical OR (||)
Here are some real-world examples where the Logical OR operator is frequently used:
1. Login Authentication
if (username.equals("admin") || username.equals("superuser")) {
System.out.println("Access granted to admin dashboard.");
}
2. Discount Eligibility
if (isStudent || hasCoupon) {
System.out.println("You are eligible for a discount.");
}
3. Alarm System
if (motionDetected || doorOpened) {
System.out.println("Security alert triggered!");
}
4. App Notification Logic
if (batteryLow || storageFull) {
System.out.println("Please check your device status.");
}
Logical NOT (!
) Operator in Java
The Logical NOT operator (!) is a unary operator which works on a single boolean value. This operator is used to invert the value of a boolean expression:
- If the expression is true, ! turns it into false.
- If the expression is false, ! turns it into true.
The general syntax to use logical NOT operator in Java is as follows:
!condition
Example 3: Using Logical NOT Operator
public class LogicalNotExample {
public static void main(String[] args) {
boolean isLoggedIn = false;
// Use the NOT operator to check if the user is NOT logged in.
if (!isLoggedIn) {
System.out.println("Please log in to continue.");
} else {
System.out.println("Welcome back!");
}
}
}
Output:
Please log in to continue.
In this example, the variable isLoggedIn is false. Therefore, !isLoggedIn becomes true. Since the condition is satisfied, the message “Please log in to continue.” is printed on the console.
Real-World Use Cases of Logical NOT (!)
Here are some real-world scenarios where the NOT operator is commonly used:
1. Access Control
boolean isAuthenticated = false;
if (!isAuthenticated) {
System.out.println("Redirecting to login page...");
}
2. Form Validation
boolean isFormValid = false;
if (!isFormValid) {
System.out.println("Please complete all required fields.");
}
3. Feature Toggle
boolean isFeatureEnabled = true;
if (!isFeatureEnabled) {
System.out.println("This feature is currently disabled.");
}
Logical Short-Circuit AND Operator (&&)
The logical short-circuit AND operator (&&) is used in the form
operand1 && operand2
The logical short-circuit AND operator returns true if both operands are true. If either operand is false, it returns false. It is called a short-circuit AND operator because if the left-hand operand1 evaluates to false, it returns false without evaluating the right-hand operand operand2.
Example 4:
int i = 10;
int j = 15;
boolean b = (i > 5 && j > 10); // Assigns true to b
In this example, the expression i > 5 is evaluated first and it returns true. Since the left hand operand evaluated to true, the right hand operand was also evaluated. The right-hand operand, j > 10, is evaluated, which also returns true. Now, the expression is reduced to true && true. Since both operands are true, the final outcome is true.
Example 5:
int i = 10;
int j = 15;
boolean b = (i > 20 && j > 10); // Assigns false to b
In this example, the expression i > 20 returns false. The expression reduces to false && j > 10. Since the left-hand operand is false, the right-hand operand, j > 10, is not evaluated and && returns false. However, there is no way to prove in the above example that the right-hand operand, which is j > 10, was not evaluated.
Logical Short-Circuit OR Operator (||)
The logical short-circuit OR operator (||) is used in the form
operand1 || operand2
The logical short-circuit OR operator returns true if either operand is true. If both operands are false, it returns false. It is called a short-circuit OR operator because if operand1 evaluates to true, it returns true without evaluating operand2.
Example 6:
int i = 10;
int j = 15;
boolean b = (i > 5 || j > 10); // Assigns true to b
In the above example, the expression i > 5 is evaluated first, and it returns true. Since the left-hand operand evaluated to true, the right hand operand is not evaluated, and the expression (i > 5 || j > 10) returns true.
Example 7:
int i = 10;
int j = 15;
boolean b = (i > 20 || j > 10); // Assigns true to b
In this example, the expression i > 20 returns false. The expression reduces to false || j > 10. Since the left-hand operand to || is false, the right-hand operand, j > 10, is evaluated, which returns true and the entire expression returns true.
Advanced Examples of Logical Operators in Java
Let’s take some advanced example programs based on the logical operators in Java.
Example 8: Driving Eligibility Check
public class DrivingEligibility {
public static void main(String[] args) {
int age = 22;
boolean hasLicense = true;
boolean isSober = true;
// Check all conditions using logical AND (&&).
if ((age > 18 && hasLicense) && isSober) {
System.out.println("Allowed to drive.");
} else {
System.out.println("Not allowed to drive.");
}
}
}
Output:
Allowed to drive.
In this example, the first condition age > 18 returns true because 22 is greater than 18. The second condition hasLicense is also evaluated to true. The thrid condition isSober evaluates to true. Since all conditions are true i.e. (true && true) && true = true, the output is: “Allowed to drive.”.
Example 9: Short-Circuit Evaluation with &&
public class ShortCircuitExample {
// Method to simulate verification.
public static boolean isVerified() {
System.out.println("Verification Checked");
return true;
}
public static void main(String[] args) {
// false && anything → short-circuits, method won't be called.
if (false && isVerified()) {
System.out.println("Access Granted");
} else {
System.out.println("Access Denied");
}
}
}
Output:
Access Denied
In this example, the condition is false && isVerified(). Since the first operand (false) is already false, Java short-circuits the evaluation. That means isVerified() is never called. So, “Verification Checked” is not printed on the console. Only “Access Denied” is printed on the console.
Multiple Choice Questions (MCQs) on Logical Operators
Q1. What is the output of the below code?
javaCopyEditint a = 5, b = 10;
System.out.println(a > 3 && b < 15);
- a) true
- b) false
- c) Compilation error
- d) Runtime error
Answer: a) true
Q2. Which operator has the highest precedence?
- a) ||
- b) &&
- c) !
- d) ==
Answer: c) !
Q3. What is the output of the below Java code?
javaCopyEditSystem.out.println(true || false && false);
- a) false
- b) true
- c) Compilation error
- d) Runtime error
Answer: b) true
Frequently Asked Questions on Logical Operators
1. Can we use logical operators with non-boolean types in Java?
Answer: No, Java strictly allows logical operators only on boolean expressions.
2. What is the difference between &&
and &
?
&&
is logical AND with short-circuiting, while &
is bitwise AND without short-circuiting.
3. Can I chain multiple logical expressions?
Yes, but use parentheses for clarity: if ((x > 10 && y < 20) || z == 5)
4. Why do you use short-circuiting?
Short-circuiting improves performance by skipping unnecessary evaluations and avoids potential errors like null pointer exceptions.