Logical operators are used to test the validity of one or more expressions. The return value of these expressions is a boolean value, true or false. In Java, we have the following logical operators:
- AND (&&)
- OR (||)
- NOT (!)
AND operator
The AND operator is used in cases where we have two or more expressions and we need all of them to be true, meaning that their return is true.
For example:
1 2 3 4 |
int a = 10; int b = 15; int c = 200; System.out.println(c > a && c > b); |
Here we have two expressions c > a and c > b and the AND operator is used to make sure that the value of c is greater than the two values of the remaining two variables a and b.
OR operator
The OR operator is also used in cases where we have two or more expressions and we need only one of them to be true, meaning that the value is true. The remaining expressions can be true or false, but at least one must be true.
For example:
1 2 3 4 |
int a = 10; int b = 15; int c = 200; System.out.println(c > a || b > c); |
In this example, we just need c, greater than a, is fine, b can be less or greater than c, not important 😀
NOT operator
The NOT operator is used to reverse the result of one or more expressions that return boolean values. Meaning that if any expression returns true, using the NOT operator will result in the opposite of true, false.
For example:
1 2 3 |
int a = 10; int b = 15; System.out.println(!(a > b)); |
The result of this example is true because a is not greater than b, false, the inverse is true.
To give you a better understanding of the results of expressions used with logical operators, I give the following table, we often call it the truth table
Toán tử AND (&&) | Toán tử OR (||) | Toán tử NOT (!) |
true && true => true | true || true => true | !true => false |
true && false => false | true || false => true | !false => true |
false && true => false | false || true => true | |
false && false => false | false || false => false | |
true && true && false => false | false || false || true => true |
Looking at the table above we can see:
- The AND operator can only return true if all the results of the expression are true, if one of them is false then the result is false.
- The OR operator only returns false if all the results of the expression are false; otherwise, just one expression is true and the result is true.
- The NOT operator reverses the boolean result.