Let’s learn logical operators in java.
Logical operators in java
Logical operators combine multiple conditional statements which returns boolean (true/false) output. Logical operators are very similar to OR gate and AND gate in digital electronics.
Logical operators is only applicable for boolean types. There are three types of 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
condition1 | condition2 | condition1 && condition2 |
true | true | true |
false | true | false |
true | false | false |
false | false | false |
Example:
Let’s see java program on Logical AND (&&) operator.
public class LogicalANDOperator { public static void main(String[] args) { boolean b1 = true; boolean b2 = true; if(b1 && b2) { System.out.println("True"); } else { System.out.println("False"); } } }
Output:
True
Logical OR (||) operator: logical OR (||) returns true only when one of the conditions are true.
Syntax: condition1 || condition2
condition1 | condition2 | condition1 || condition2 |
true | true | true |
false | true | true |
true | false | true |
false | false | false |
Example:
Let’s see java program on Logical OR (||) operator.
public class LogicalOROperator { public static void main(String[] args) { boolean b1 = false; boolean b2 = true; if(b1 || b2) { System.out.println("True"); } else { System.out.println("False"); } } }
Output:
True
Logical NOT (!) operator: logical NOT (!) returns true if condition is false and if condition is true it returns false. Logical NOT (!) operator is an unary operator.
Syntax: !(condition)
condition1 | !condition1 |
true | false |
false | true |
Example:
Let’s see java program on Logical NOT (!) operator.
public class LogicalNOTOperator { public static void main(String[] args) { boolean b1 = false; boolean b2 = true; System.out.println("b1 is : " + b1); System.out.println("b2 is : " + b2); System.out.println("Not (!b1) is : " + !b1); System.out.println("Not (!b2) is : " + !b2); } }
Output:
b1 is : false
b2 is : true
Not (!b1) is : true
Not (!b2) is : false
Also read – interface in java