More Boolean Expressions in Comparisons
Explore how to create and combine Boolean expressions using relational and logical operators such as and, or, and not. Understand short-circuit evaluation and operator precedence to write clearer and efficient conditional statements in Java.
We'll cover the following...
As we mentioned earlier, an expression such as age >= 20, that we use as the condition within an if statement is called a Boolean expression. These simple expressions use the relational operators given earlier in this table to compare two operands—variables, constants, or other expressions—that have primitive data types. Each expression has a value of true or false.
Logical operators
We can combine Boolean expressions into more complex Boolean expressions by using the logical operators &&, ||, and !. These operators are named and, or, and not, respectively, and behave as follows:
📝 Note: The logical operators
&&,||, and!
The “and” operator: The expression
boolean-expression1
&&boolean-expression2is true if both Boolean expressions are true; otherwise, it is false.
The “or” operator: The expression
boolean-expression1
||boolean-expression2is true if either or both Boolean expressions are true; otherwise, it is false.
The “not” operator: The expression
!boolean-expressionis true if the Boolean expression is false; otherwise, it is false. ...