Introduction
Comparison operators compare two values and return a bool (true or false). They are the backbone of decision-making in programs — every if statement uses them.
Why It Matters
Without comparison operators, you cannot build logic like "if the user is older than 18" or "if the password is correct." Every conditional statement in Dart depends on a boolean expression formed by comparison operators.
Comparison Operators
| Operator | Name | Example | Result |
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 3 | true |
> | Greater than | 7 > 3 | true |
< | Less than | 2 < 9 | true |
>= | Greater than or equal | 5 >= 5 | true |
<= | Less than or equal | 4 <= 6 | true |
Code Example
void main() {
int a = 10;
int b = 20;
print(a == b); // false
print(a != b); // true
print(a > b); // false
print(a < b); // true
print(a >= 10); // true
print(b <= 20); // true
// Used in conditions
int age = 17;
if (age >= 18) {
print('Access granted');
} else {
print('Access denied');
}
// Comparing strings
String lang = 'Dart';
print(lang == 'Dart'); // true
print(lang == 'Python'); // false
}
Output:
false
true
false
true
true
true
Access denied
true
false
Explanation
== checks value equality. For objects, it checks if both references point to the same value (Dart overrides == for common types like String and int).
!= is the opposite of ==.
> and < compare numeric magnitude or lexicographic order for strings.
>= and <= include the boundary value in the comparison.
Notes
- Dart uses
== for value comparison. Unlike Java, you do NOT need .equals() for strings.
- All comparison operators return
bool — they never return numbers.
- You can compare objects of custom classes by overriding the
== operator.
Common Mistakes
- Using
= instead of == in a condition — this is an assignment, not a comparison.
- Comparing objects with
== expecting reference equality — Dart compares by value for built-in types.
- Expecting string comparison to be case-insensitive —
'dart' == 'Dart' is false.
💪 Exercise
- Write a program that checks whether a temperature
double temp = 37.5 is above, below, or equal to normal body temperature (36.6).
- Compare two strings
'apple' and 'banana' for equality and inequality.
- Check if the number 100 is both greater than 50 AND less than 200 using two separate comparisons.
🧠 Quiz
1. What does 'Dart' == 'dart' return?
- A) true
- B) false ✅
- C) error
- D) null
2. Which operator checks if two values are NOT equal?
- A) !==
- B) <>
- C) != ✅
- D) not=
Summary
Comparison operators in Dart (==, !=, >, <, >=, <=) compare two values and always return a bool. They are essential for writing conditional logic. Remember that Dart compares strings by value using ==, and always use == (double equals) for comparison, not = (single equals) which is assignment.