Java logical operators
Created By: chatGPT
In Java, logical operators are used to combine multiple Boolean expressions. These operators return a Boolean value:
true
or false
. The three main logical operators are AND, OR, and NOT.1. Logical AND (
&&
): This operator returns true
only if both operands are true
.boolean a = true;
boolean b = false;
boolean result = a && b; // result will be false
2. Logical OR (
||
): This operator returns true
if at least one of the operands is true
.boolean a = true;
boolean b = false;
boolean result = a || b; // result will be true
3. Logical NOT (
!
): This operator negates the value of the boolean expression. If the expression is true
, it returns false
, and vice versa.boolean a = true;
boolean result = !a; // result will be false
You can also combine these operators to form more complex expressions. Parentheses can be used to control the order of evaluation.
boolean a = true;
b = false;
boolean result = (a && b) || (!a); // result will be true
Here is an example that demonstrates the use of logical operators in a conditional statement:
boolean isAdult = true;
boolean hasPermission = false;
if (isAdult || hasPermission) {
System.out.println("Access granted.");
} else {
System.out.println("Access denied.");
} // This will print 'Access granted.'