Java logical operators are used to perform logical operations on boolean expressions or variables. These operators evaluate two or more conditions and return a boolean result (true
or false
).
Logical Operators in Java
Operator | Name | Description |
---|---|---|
&& |
Logical AND | Returns true if both conditions are true, otherwise returns false . |
` | ` | |
! |
Logical NOT | Reverses the boolean value of an expression (negation). |
& |
Bitwise AND (Logical) | Similar to && , but evaluates both operands even if the first is false. |
` | ` | Bitwise OR (Logical) |
^ |
Logical XOR | Returns true if one condition is true and the other is false, otherwise returns false . |
Examples of Logical Operators
1. Logical AND (&&
)
public class LogicalOperators {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
// Using Logical AND
if (a < b && b < c) {
System.out.println("Both conditions are true");
} else {
System.out.println("One or both conditions are false");
}
}
}
Output:
Both conditions are true
2. Logical OR (||
)
public class LogicalOperators {
public static void main(String[] args) {
int a = 10, b = 20;
// Using Logical OR
if (a > b || a < b) {
System.out.println("At least one condition is true");
} else {
System.out.println("Both conditions are false");
}
}
}
Output:
At least one condition is true
3. Logical NOT (!
)
public class LogicalOperators {
public static void main(String[] args) {
boolean isAvailable = false;
// Using Logical NOT
if (!isAvailable) {
System.out.println("The condition is false");
}
}
}
Output:
The condition is false
4. Logical XOR (^
)
public class LogicalOperators {
public static void main(String[] args) {
boolean condition1 = true;
boolean condition2 = false;
// Using Logical XOR
if (condition1 ^ condition2) {
System.out.println("One condition is true and the other is false");
} else {
System.out.println("Both conditions are either true or false");
}
}
}
Output:
One condition is true and the other is false
5. Bitwise AND (&
) and OR (|
) as Logical Operators
public class LogicalOperators {
public static void main(String[] args) {
int a = 10, b = 20;
// Bitwise AND and OR used logically
if (a < b & b > 0) {
System.out.println("Both conditions are evaluated and true");
}
if (a > b | b > 0) {
System.out.println("Both conditions are evaluated, and one is true");
}
}
}
Output:
Both conditions are evaluated and true
Both conditions are evaluated, and one is true
Key Points
- Short-Circuiting with
&&
and||
:&&
stops evaluating if the first condition isfalse
.||
stops evaluating if the first condition istrue
.
- Bitwise Operators Used Logically:
&
and|
always evaluate both conditions, regardless of the result.
- XOR (
^
):- Returns
true
only if the conditions differ (one is true, the other is false).
- Returns
These logical operators are fundamental in making decisions in Java programs by combining and evaluating conditions effectively.