In this lesson, you will learn
Logical operators in Java are used to perform logical operations on boolean values. They allow you to combine multiple boolean expressions and produce a single result.
The main logical operators in Java includes:
&&):Returns true if both operands are true.
boolean a = true;
boolean b = false;
boolean resultAND = (a && b); // false
||):Returns true if at least one of the operands is true.
boolean x = true;
boolean y = false;
boolean resultOR = (x || y); // true
!):Returns true if the operand is false and vice versa. It negates the boolean value.
boolean isSunny = true;
boolean resultNOT = !isSunny; // false
| Operators | Name | Description | Result e.g. x=7, y=3 |
| && | Short-circuit OR | Compare two boolean expressions and return true if any one of the boolean expression is true. | x>y&&x!=y; //false |
| || | Short-circuit AND | Compare two boolean expressions and return true if any one of the boolean expressions is true. | x>y&&x!=y; //true |
| ! | Logical unary NOT | Reverse a value | !(x<y); //true |
Logical operators are often used in control flow statements and boolean expressions to make decisions based on multiple conditions.
Here’s an example using logical operators in an if statement:
int age = 25;
boolean isStudent = true;
if (age > 18 && isStudent) {
System.out.println("You are an adult student.");
} else if (age > 18 || isStudent) {
System.out.println("You are either an adult or a student.");
} else {
System.out.println("You are neither an adult nor a student.");
}
In this example, the logical AND (&&) and logical OR (||) operators are used to combine conditions and determine the appropriate message to be printed based on the values of age and isStudent.
Understanding and using logical operators are fundamental for writing conditional expressions in Java.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.