Java Logical Operators
In Java, logical operators are used to perform logical operations on boolean values (true or false). They are mostly used in decision-making statements such as if, while, and for loops to control how a program executes based on conditions.
Logical operators combine multiple boolean expressions and determine the final outcome as either true or false.
List of Logical Operators in Java
Operator | Description | Example |
&& (Logical AND) | Returns true only if both operands are true. | (A && B) is true if both A and B are true |
|| (Logical OR) | Returns true if any one of the operands is true. | (A || B) is true if either A or B is true |
! (Logical NOT) | Reverses the logical value of the operand. | !A is true if A is false |
Example 1: Logical AND Operator
public class Test {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a && b));
}
}a && b = false
Example 2: Logical OR Operator
public class Test {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a || b = " + (a || b));
}
}a || b = true
Example 3: Logical NOT Operator
public class Test {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("!(a && b) = " + !(a && b));
}
}!(a && b) = true
Summary Table
Operator | Meaning | Result Condition |
&& | Logical AND | True only if both operands are true |
|| | Logical OR | True if at least one operand is true |
! | Logical NOT | True if operand is false |