Java Logical Operators
https/:/www.theitroad.com
Java logical operators are used to combine one or more boolean expressions and return a boolean value. The following are the logical operators in Java:
- Logical AND:
&&
The logical AND operator returnstrue
if and only if both the left and the right operands aretrue
.
boolean a = true; boolean b = false; boolean result = a && b; // result is false
- Logical OR:
||
The logical OR operator returnstrue
if at least one of the left or the right operands istrue
.
boolean a = true; boolean b = false; boolean result = a || b; // result is true
- Logical NOT:
!
The logical NOT operator returns the opposite boolean value of the operand.
boolean a = true; boolean result = !a; // result is false
These operators can be used to form more complex boolean expressions. Here's an example that uses all three operators:
boolean a = true; boolean b = false; boolean c = true; boolean result = (a && b) || (!c); // result is false
In this example, the expression (a && b)
evaluates to false
, and the expression (!c)
evaluates to false
. Therefore, the overall expression evaluates to false
, which is assigned to the variable result
.