Logical Operators
In Java, logical operators perform logical operations on boolean operands. Java supports three logical operators:
- Logical AND (
&&
) - Logical OR (
||
) - Logical NOT (
!
)
Logical AND (&&
)
This operator returns true
if both operands are true
, otherwise, it returns false
.
If the first operand evaluates to false
, the second operand is not evaluated because the result will always be false
.
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
logicalAnd(a, b);
}
public static void logicalAnd(boolean a, boolean b) {
boolean result = a && b; // result will be false
System.out.println(result);
}
}
Logical OR (||
)
This operator returns true
if at least one of the operands is true
, otherwise, it returns false
.
If the first operand evaluates to true
, the second operand is not evaluated because the result will always be true
, if the first operand happens to be false
, then the second operand is evaluated to see if its true
or false
.
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
logicalOR(a, b);
}
public static void logicalOR(boolean a, boolean b) {
boolean result = a || b; // result will be true
System.out.println(result);
}
}
Logical NOT (!
)
This operator is a unary operator and is used to invert the value of a boolean expression.
It returns true
if the operand is false
, and false
if the operand is true
.
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true;
logicalNOT(a);
}
public static void logicalNOT(boolean a) {
boolean result = a; // result will be false
System.out.println(result);
}
}
Logical operators are commonly used in conditional statements (if
, else
, while
, do-while
, etc.) and boolean expressions to control the flow of the program based on certain conditions. They allow for the creation of complex conditions by combining simpler conditions.