Comparison Operators are often used in control flow statements in Java. The control flow statements include decision-making statements (if, switch), looping statements (for, while, do-while), and branching statements (break, continue). The following lessons deal with these topics, respectively.
Let us begin by understanding how comparison operators work.
Typically, control flow statements perform some form of comparison. The direction of the program depends on such comparisons.
The most commonly known and widely used comparison operator is the equality operator. If a programmer wishes to compare two variables and determine if they are equal, the == operator (double =) is used. If a==b is typed, the compiler is being asked to compare both the variables for equality.
In case they are found to be equal, true is returned. Or else, the statement is deemed to be false.
Other than the equality operator, several other comparison operators can help with the control flow statements.
Not equal (!=)
If the left side is not equal to the right, the result is true!
8 != 9 is true 8 != 8 is false
Greater than (>)
In case the left side is greater than the right, the result is true.
7 > 5 will give true 2 > 8 will give false
Less than (<)
If the left side is smaller than the right, the result is true.
4 < 11 returns true 30 < 6 is false
Greater than or equal to (>=)
If the left side of the expression is either greater than or equal to the right, the result is true.
7 >= 2 returns true 7 >= 7 returns true 2 >= 7 returns false
Less than or equal to (<=)
If the expression’s left side is less than or equal to the one on the right, the result is true.
2 <= 4 returns true 4 <= 4 returns true 12 <= 4 returns false
There are two logical operators (&&, ||) that serve their purpose when merging a few conditions.
The AND operator (&&)
For a statement containing the && operator to return true, all conditions have to be met. For instance,
3==3 && 7>2 && 2!=5 will return true as all the conditions are true 5==5 && 7<1 && 4!=8 will return false since the second condition (7<1) is false
The OR operator (||)
Even if one condition is true, the result is true.
5==5 || 9<3 || 7!=7 will return true because the first condition (5==5) is true 7==6 || 5<3 || 5==7 will return false because none of the conditions are true