What is logical operators in Java?
Logical operators in Java are used to perform logical operations on boolean expressions. These operators return a boolean result (true or false) based on the logical relationship between the operands.
The main logical operators in Java are:
- AND (&&)
- OR (||)
- NOT (!)
1. AND (&&) #
The && operator returns true if both operands are true. If any one of the operands is false, the result will be false.
Example:
public class LogicalOperatorExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
/* Check if a is less than 15
AND b is greater than 15 */
if (a < 15 && b > 15) {
System.out.println("Both conditions are true");
} else {
System.out.println("At least one condition is false");
}
}
}
Output:
Both conditions are true
In this example, a < 15 is true and b > 15 is also true. Since both conditions are true, the output is “Both conditions are true”.
2. OR (||) #
The || operator returns true if at least one of the operands is true. It only returns false when both operands are false.
Example:
public class LogicalOperatorExample {
public static void main(String[] args) {
int a = 10;
int b = 5;
// Check if a is greater than 15 OR b is less than 10
if (a > 15 || b < 10) {
System.out.println("At least one condition is true");
} else {
System.out.println("Both conditions are false");
}
}
}
Output:
At least one condition is true
In this example, a > 15 is false, but b < 10 is true. Since one condition is true, the output is “At least one condition is true”.
3. NOT (!) #
The ! operator negates the value of the boolean expression. If the expression is I, it returns false, and if the expression is false, it returns true.
Example:
public class LogicalOperatorExample {
public static void main(String[] args) {
boolean condition = false;
// Check if the condition is NOT true
if (!condition) {
System.out.println("Condition is false");
} else {
System.out.println("Condition is true");
}
}
}
Output:
Condition is false
In this example, condition is false, and the ! operator negates it to true. Hence, the output is “Condition is false”.
Combining Logical Operators #
You can combine logical operators to evaluate complex conditions.
Example:
public class LogicalOperatorExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 5;
/* Check if a is less than 15 AND
(b is greater than 15 OR c is greater than 10) */
if (a < 15 && (b > 15 || c > 10)) {
System.out.println("Complex condition is true");
} else {
System.out.println("Complex condition is false");
}
}
}
Output:
Complex condition is true
In this example, the complex condition evaluates to true because a < 15 is true and b > 15 is true (making the whole expression within the parentheses true).
These logical operators are fundamental in controlling the flow of your program by making decisions based on multiple conditions.