Using Boolean Expressions and Relational Operators
As you saw in the algorithm section, an algorithm is comprised of sequential steps, conditionals, and iterative processes.
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.
Relational Operators
The relational operators compare values and evaluate to either true or false. They can be used in boolean expressions. 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
Let's try it in the Java Playground.
- Predict the result of the program code.
- Run the code to check your predictions.
Boolean Expressions
In Boolean expressions, 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.
Your Turn
Let's try it in the Java Playground.
- 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.
Resources
Practice: Using Relational Operators
Next Learn Tutorial
Learn: Introduction to Logic Operators