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

OperatorMeaningExampleResult
==Equal to10 == 10true
!=Not equal to10 != 5true
>Greater than10 > 5true
<Less than5 < 10true
>=Greater than equal10 >= 10true
<=Less than equal5 <= 10true

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

  1. Write a program to check whether a number is greater than 100
  2. Compare two numbers and print which one is larger
  3. Take temperature and check if it is below 0
  4. Compare two characters and print result