Comparison Operators
3 min read ·
Comparison operators are used to compare two values.
They always return a boolean value which is either true or false.
These operators are mostly used inside if statements, loops and conditional logic.
Comparison Operators Table
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 10 == 10 | true |
| != | Not equal to | 10 != 5 | true |
| > | Greater than | 10 > 5 | true |
| < | Less than | 5 < 10 | true |
| >= | Greater than equal | 10 >= 10 | true |
| <= | Less than equal | 5 <= 10 | true |
1 Equal To Operator ==
Checks whether two values are equal.
Example
Output
true
2 Not Equal To Operator !=
Checks whether two values are different.
Output
true
3 Greater Than Operator >
Checks if left value is greater than right value.
Output
true
4 Less Than Operator <
Checks if left value is less than right value.
Output
true
5 Greater Than Equal To Operator >=
Checks if value is greater than or equal to another value.
Output
true
6 Less Than Equal To Operator <=
Checks if value is less than or equal to another value.
Output
false
Using Comparison Operators in If Statement
Important Concept
Comparison operators work with primitive data types like int, double, float, char and long.
When comparing characters, Java compares their ASCII values.
Output
true
Because ASCII value of A is less than B.
Caution
Do not confuse = with ==. Single equal sign assigns value. Double equal sign compares value.
Real World Example
Checking Voting Eligibility
Practice Exercise
- Write a program to check whether a number is greater than 100
- Compare two numbers and print which one is larger
- Take temperature and check if it is below 0
- Compare two characters and print result