Logical Operators
COMP 1010 Home > Java Fundamentals
IntroductionAll the standard comparison operators work for primitive values (int, double, char, ...). In this section, we will be discussing three logical operators: &&, || and !
|
---|
{{{Body}}}
Logical Operators
The && operator
Java provides an easy way to handle multiple conditions: && - is logical which combines two boolean values and returns a boolean which is true if and only if both of its operands are true. For instance,
Example 1:
boolean b; b = 3 > 2 && 5 < 7; // b is true b = 2 > 3 && 5 < 7; // b is now false
In the first part of example one, 3 is greater than 2 and 5 is less than 7. Since both expressions are true, the variable gets the value as true. In the second part, 2 is not greater than 3, even though 5 is less than 7. So the value of variable b is false.
The || operator
|| is logical or. || combines two boolean variables or expressions and returns a result which is true if either or both of its operands are true. For instance,
Example 2:
boolean b; b = 3 > 2 || 5 > 7; // b is true b = 2 > 3 || 5 < 7; // b is still true b = 2 > 3 || 5 > 7; // now b is false
In first part of example two, 3 is greater than 2 so the value of the expression on the left of || operator is true. Even though 5 is less than 7 and the value of this expression is false, the variable gets the value as true. This is because if either of the statements is true in an OR operator, the result is true. In the second part even though 2 is less than 3, the other expression with it is true, so the variable b now gets the value as true. In the third part, 2 is less than 3 and 5 is less than 7, so with two false values, the result is also false.
The ! operator
The third logical operator is ! which means not. It reverses the value of a boolean expression, which means that if b is true, !b is false. If b is false !b is true.
Example 3:
boolean b; b = !(3 > 2); // b is false b = !(2 > 3); // b is true
In first part of example three, 3 is greater than 2 and value of the expression is true and !true = false. Similarly, in the second part, 2 is less than 3 is false and the !false = true.
One thing to note is, unlike arithmetic operators which deal with primitive data types, logical operators compare two expressions where each gives the value as either true or false.
Table of Logical Operators
The next three tables give the behaviour of the logical operators.
&& (and) operator | || (or) operator | ! (not) operator | |||||||||||||||||||||||||||||||||
|
|
|