Let’s learn logical operators in java.
Logical operators in java
Logical operators combine more than two conditions which returns boolean output. Logical operators are very similar to OR gate and AND gate in digital electronics.
Below are logical operators,
- Logical AND (&&) operator
- Logical OR (||) operator
- Logical NOT (!) operator
Logical AND (&&) operator: logical AND (&&) returns true only when both the conditions are true.
Syntax: condition1 && condition2
Example:
a = 40, b = 10, c = 10, d = 0 condition1 - a > b condition2 - b == c if(a > b && b == c) d = a + b since both conditions is true. Output is 50
Let’s see java program on Logical AND (&&) operator.
public class LogicalANDOperator { public static void main(String[] args) { System.out.println((40 > 20) && (70 > 50)); System.out.println((30 > 10) && (60 < 40)); } }
Output:
true
false
Logical OR (||) operator: logical OR (||) returns true only when one of the conditions are true.
Syntax: condition1 || condition2
Example:
a = 40, b = 10, c = 10, d = 0 condition1 - a > b condition2 - b < c if(a > b || b < c) d = a + b since one of the conditions is true. Output is 50
Let's see java program on Logical OR (||) operator.
public class LogicalOROperator { public static void main(String[] args) { System.out.println((70 < 40) || (90 > 60)); System.out.println((80 < 20) || (100 < 50)); } }
Output:
true
false
Logical NOT (!) operator: logical NOT (!) returns true when condition is false and when condition is true returns false. Logical NOT (!) operator is an unary operator.
Syntax: !(condition)
Example:
a = 40, b = 20 !(a < b) // returns true !(a > b) // returns false
Let's see java program on Logical NOT (!) operator.
public class LogicalNOTOperator { public static void main(String[] args) { System.out.println(!(70 == 40)); System.out.println(!(70 > 40)); } }
Output:
true
false
Also read - interface in java