Using Boolean Expressions and Relational Operators
As you saw in the algorithm section, an algorithm is comprised of sequential steps, conditionals, and iterative processes. Sequential steps are those done in order. Conditionals allow the program to behave in different ways based on decisions. Iterative processes repeat series of steps.
In this tutorial we will focus on Boolean expressions, which are critical to conditionals and iterative processes.
Boolean Expressions
Recall that a boolean
variable is assigned either true
or false
. A Boolean expression is any expression that can be evaluated to a boolean value, true
or false
. They are comprised of relationship operators and logic operators.
Relationship Operators
The relationship operators compare values and evaluate to either true
or false
. They are as follows:
Operator |
Name |
Description |
Example |
>
|
greater than |
evaluates to true if the value on the left is greater than the value on the right and false otherwise. |
3 > 5 evaluates to false
5 > 3 evaluates to true
5 > 5 evaluates to false since the values are equal
|
<
|
less than |
evaluates to true if the value on the left is less than the value on the right and false otherwise. |
3 < 5 evaluates to true
5 < 3 evaluates to false
5 < 5 evaluates to false since the values are equal
|
>=
|
greater than or equal to |
evaluates to true if the value on the left is greater than or equal to the value on the right and false otherwise. |
3 >= 5 evaluates to false
5 >= 3 evaluates to true
5 >= 5 evaluates to true since the values are equal
|
<=
|
less than or equal to |
evaluates to true if the value on the left is less than or equal to the value on the right and false otherwise. |
3 <= 5 evaluates to true
5 <= 3 evaluates to false
5 <= 5 evaluates to true since the values are equal
|
==
|
equal to |
evaluates to true if the values are equal to each other and false otherwise. |
3 == 5 evaluates to false
5 == 5 evaluates to true since the values are equal
|
!=
|
not equal to |
evaluates to true if the values are not equal to each other and false otherwise. |
3 != 5 evaluates to true
5 != 5 evaluates to false
|
Your Turn
- Predict the result of the program code.
- Run the code to check your predictions.
Try these out in the Java Playground. Take a few minutes to change the values and see the new results.
Your Turn
- Predict the result of the program code.
- Run the code to check your predictions.
- Write a few more statements that use arthimetic expressions and relational operators.
- Predict the result of these statements.
- Run the code to check your predictions.
The values being compared could be variables, expressions, or values. In these examples, we have integrated variables and expressions. Take a few minutes to change the values and see the new results.
Resources
Practice: Using Relational Operators