Logical Expressions
In this lesson, an explanation of the use of logical expressions in Java programs is provided.
We'll cover the following...
Introduction
Logical expressions are also known as Boolean expressions. It will always evaluate to a value of either true or false. Therefore, they will be represented by the data type boolean. While they may seem similar to mathematical operators, the difference lies in how they are used with comparative or boolean operators. Let’s look at both types of operators in detail.
Comparative operators
Java has several operators that can be used to compare value. Comparison implies knowing which value is greater than the other, or equal to it, and so on. The table below shows the entire list of operators available in Java.
| Symbols | Comparative operators |
|---|---|
| < | Less than |
| > | Greater than |
| <= | Less than or equal to |
| >= | Greater than or equal to |
| == | Equal to |
| != | Not equal to |
Note here that these comparative operators can be used on any primitive data type except for boolean.
Now that we have an idea of what these operators are let’s see how we can use them in code.
Boolean operators
These operators rely on boolean algebra. Hence, boolean operators will work directly on boolean values. There are four types of boolean operators. Let’s first look at their symbols and what they are in the table below before we discuss what functionality they perform.
| Symbols | Boolean operators |
|---|---|
| ! | Boolean NOT |
| && | Boolean AND |
| || | Boolean OR |
| ^ | Boolean exclusive XOR |
- The
boolean NOTinverts the value of the boolean expression that follows it. - The
boolean ANDwill return true if and only if, expressions on both sides of the operator are true. - The
boolean ORwill return true if the expression on either or both sides of the operator is true. - The
boolean exclusive XORwill return true if one of the expressions evaluates to true and the other to false.
Now that we have some understanding of these operators let’s see how to use them in code.
Let’s assess our understanding of this lesson with the following question:
Question:Evaluate the following complex logical expression involving both boolean and comparative operators:
Provide the correct result by applying the rules of both boolean and comparative operator precedence, taking into account the effect of the parentheses.
Note: Write your answer in the space provided below.