On this page28 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. What Is a Comparison?
- 2. The Six Comparison Operators
- 3. == and !=
- 4. Greater Than and Less Than
- 5. The "Or Equal" Operators
- 6. Storing the Result
- 7. Comparing int and double
- 8. The double Trap
- 9. Comparing Strings
- 10. Strings Have No < or >
- 11. Comparing bool Values
- 12. Comparing Different Types
- 13. Comparing with null
- 14. One Comparison at a Time
- 15. identical() — The Same Object?
- 16. A Real-World Example
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Quick Revision
- Key Takeaways
- What's Next?
Lecture 18 — Comparison & Equality
| Category | 4 — Operators |
| Lecture | 018 of 140 |
| Estimated video length | 9 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
Until now our programs could calculate a total, but not ask whether it was too much. Comparison operators ask yes-or-no questions about values, and answer with
trueorfalse.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways
Every error message in this lecture is real. Each one was produced by running the code shown on Dart 3.12.2, so you will recognize it when you meet it yourself.
Prerequisites
Students should already understand, from Lectures 001–017:
- variables,
var, and the typesint,double,String, andbool - string interpolation with
$nameand${...} - string methods such as
toLowerCase()andtrim(), andlength - number methods such as
abs(), and why0.1 + 0.2is not exactly0.3 int.parse()andruntimeType- nullable types (
int?,String?) and the??operator - arithmetic and assignment operators
Connection With Previous Lectures
In Lecture 017 we learned to calculate:
int total = 400 * 3;The program now knows the total is 1200. But it cannot tell us whether 1200 is more than
our budget, whether a student's marks reach the pass mark, or whether the password someone
typed matches the real one. Every one of those is a question about two values. Arithmetic
operators produce new numbers; we need operators that produce answers.
Learning Objectives
By the end of this lecture you will be able to:
- Understand that a comparison produces a
boolvalue - Use the six comparison operators:
==,!=,>,<,>=, and<= - Store the result of a comparison in a
boolvariable - Compare
intanddoublevalues, and explain why1 == 1.0istrue - Compare strings safely, including ignoring capital letters and spaces
- Compare nullable values with
null - Recognize what
identical()checks - Recognize the error messages Dart produces for common comparison mistakes
1. What Is a Comparison?
A comparison asks a yes-or-no question about two values. The answer is always a bool:
true or false.
Analogy — think of a pair of scales. You put one value on each side, and the scales answer only one thing: is this side heavier, lighter, or the same? They never answer with a number.
void main() {
print(10 > 5);
print(3 > 8);
}true
false10 > 5 asks "is 10 greater than 5?" — yes, so true.
2. The Six Comparison Operators
| Operator | Question it asks | Example | Result |
|---|---|---|---|
== | equal to? | 5 == 5 | true |
!= | not equal to? | 5 != 5 | false |
> | greater than? | 7 > 3 | true |
< | less than? | 7 < 3 | false |
>= | greater than or equal to? | 5 >= 5 | true |
<= | less than or equal to? | 4 <= 5 | true |
== and != are called equality operators; the other four are relational operators,
because they ask how two values relate in size.
3. == and !=
== is two equals signs. It asks whether two values are equal. != asks the opposite
question, so it always gives the opposite answer.
void main() {
int a = 20;
int b = 20;
print(a == b);
print(a != b);
}true
falseRemember from Lecture 004: a single = assigns a value. Only == compares.
4. Greater Than and Less Than
void main() {
int aliAge = 20;
int saraAge = 18;
print(aliAge > saraAge);
print(aliAge < saraAge);
}true
falseRead the operator from left to right: aliAge > saraAge means "Ali's age is greater than
Sara's age".
5. The "Or Equal" Operators
> and >= differ only at the boundary — when both values are the same.
void main() {
int marks = 50;
print(marks > 50);
print(marks >= 50);
print(marks <= 50);
}false
true
trueIf the pass mark is 50, a student with exactly 50 has passed. That is >=, not >. Most
"off by one" bugs in comparisons come from picking the wrong one.
6. Storing the Result
A comparison is an expression with a bool value, so you can store it in a bool variable
and give the answer a meaningful name.
void main() {
int marks = 72;
int passMark = 50;
bool hasPassed = marks >= passMark;
print('Passed: $hasPassed');
}Passed: trueIn Lecture 022 we will use values like hasPassed with if to make the program choose
what to do. For now, we print them.
7. Comparing int and double
int and double are different types, but comparison operators compare their values.
void main() {
print(1 == 1.0);
print(10 > 9.5);
print(5 >= 5.0);
}true
true
true1 and 1.0 are the same number, so == says true — even though their types differ:
void main() {
print(1.runtimeType == 1.0.runtimeType);
}falseThe values are equal; the types (int and double) are not.
8. The double Trap
In Lecture 009 we saw that 0.1 + 0.2 is not exactly 0.3. That tiny error makes ==
fail:
void main() {
double sum = 0.1 + 0.2;
print(sum);
print(sum == 0.3);
}0.30000000000000004
falseFor calculated decimals, ask "are they close enough?" instead: the difference, made
positive with abs(), should be tiny.
void main() {
double sum = 0.1 + 0.2;
print((sum - 0.3).abs() < 0.000001);
}true9. Comparing Strings
== works on strings too. Two strings are equal only if they contain exactly the same
characters, in the same order.
void main() {
print('Ali' == 'Ali');
print('Ali' == 'ali');
print('Ali' == 'Ali ');
}true
false
falseA capital letter or a trailing space makes them different. When people type text, clean
both sides first with trim() and toLowerCase():
void main() {
String typed = ' SARA ';
String saved = 'sara';
print(typed.trim().toLowerCase() == saved);
}true10. Strings Have No < or >
>, <, >=, and <= are for numbers. Using them on strings is an error:
void main() {
print('apple' < 'banana'); // ✗
}Error: The operator '<' isn't defined for the type 'String'.
Try correcting the operator to an existing operator, or defining a '<' operator.
print('apple' < 'banana');
^You can compare something numeric about a string, such as its length:
void main() {
String password = 'dart2026';
print(password.length >= 8);
}truePutting text in alphabetical order comes later, in Lecture 045 — Sorting & Reversing Lists.
11. Comparing bool Values
bool values support == and !=, but not < or >.
void main() {
bool aliPaid = true;
bool saraPaid = false;
print(aliPaid == saraPaid);
print(aliPaid != saraPaid);
}false
truetrue > false is an error, just like < on strings: The operator '>' isn't defined for
the type 'bool'.
12. Comparing Different Types
== will compare any two values, even a string and a number. They are never equal:
void main() {
String typedAge = '20';
int realAge = 20;
print(typedAge == realAge);
print(int.parse(typedAge) == realAge);
}false
trueThere is no error — Dart just answers false, which makes this mistake easy to miss.
Convert first (Lecture 010), then compare.
13. Comparing with null
== and != are the normal way to check whether a nullable variable holds a value:
void main() {
String? middleName;
int? score = 0;
print(middleName == null);
print(score != null);
}true
true0 is a real value, not null.
About the editor warning. In a tiny program like this, Dart can see that
middleNamewas never given a value, sodart analyzewarnsThe operand must be 'null', so the condition is always 'true'.It is only a warning — the program runs. In real programs the value arrives from outside (a form, a file), and the check becomes meaningful.
But >, <, >=, and <= refuse a nullable value,
because "is nothing greater than 5?" has no answer:
void main() {
int? score;
print(score > 5); // ✗
}Error: Operator '>' cannot be called on 'int?' because it is potentially null.
print(score > 5);
^Give it a default first with ?? from Lecture 014:
void main() {
int? score;
print((score ?? 0) > 5);
}false14. One Comparison at a Time
In mathematics you might write 18 < age < 60. Dart does not allow that:
void main() {
int age = 25;
print(18 < age < 60); // ✗
}Error: A comparison expression can't be an operand of another comparison expression.
Try putting parentheses around one of the comparisons.
print(18 < age < 60);
^18 < age is already a bool, and a bool cannot be compared with < 60. Joining two
questions with "and" is exactly what Lecture 019 — Logical Operators teaches.
15. identical() — The Same Object?
== asks "are these values equal?" The function identical() asks a stricter question:
"are these the same object in the computer's memory?"
void main() {
String a = 'ali';
String b = 'ALI'.toLowerCase();
print(a == b);
print(identical(a, b));
}true
falseBoth hold the text ali, so == says true. But b was built by toLowerCase() as a new
string, so they are two separate objects. For everyday values, always use ==. Objects are
introduced in Lecture 053 — Creating Classes & Objects, and teaching your own classes what
== means comes in Lecture 060 — Method Overriding.
16. A Real-World Example
void main() {
String student = 'Zayan';
int marks = 78;
int passMark = 50;
int? bonus;
bool hasPassed = marks >= passMark;
bool isTopScore = marks == 100;
bool hasBonus = bonus != null;
bool reachedEighty = marks + (bonus ?? 0) >= 80;
print('Student: $student');
print('Passed: $hasPassed');
print('Top score: $isTopScore');
print('Has bonus: $hasBonus');
print('Reached 80: $reachedEighty');
}Student: Zayan
Passed: true
Top score: false
Has bonus: false
Reached 80: falseEach comparison is one clear question with a named answer. Notice that + runs before >=
in the last one: arithmetic first, then the comparison. The full precedence order comes in
Lecture 021.
Code Examples
Example 1 — Equal and Not Equal
void main() {
int x = 15;
int y = 20;
print(x == y);
print(x != y);
}false
trueExample 2 — All Four Relational Operators
void main() {
int a = 9;
int b = 4;
print(a > b);
print(a < b);
print(a >= b);
print(a <= b);
}true
false
true
falseExample 3 — The Boundary
void main() {
int speed = 60;
int limit = 60;
print('Over the limit: ${speed > limit}');
print('At or under the limit: ${speed <= limit}');
}Over the limit: false
At or under the limit: trueExample 4 — int Meets double
void main() {
int whole = 3;
double decimal = 3.0;
print(whole == decimal);
print(whole < 3.5);
}true
trueExample 5 — Comparing Text Fairly
void main() {
String answer = ' Dart ';
print(answer == 'dart');
print(answer.trim().toLowerCase() == 'dart');
}false
trueExample 6 — Checking for null
void main() {
String? nickname;
String? city = 'Lahore';
print(nickname == null);
print(city != null);
}true
trueExample 7 — Student Pass Check
void main() {
String name = 'Ali';
int math = 80;
int science = 75;
int english = 85;
int total = math + science + english;
int passTotal = 150;
print('Student: $name');
print('Total: $total');
print('Passed: ${total >= passTotal}');
}Student: Ali
Total: 240
Passed: trueHow it works
totalis calculated first:80 + 75 + 85is240.total >= passTotalasks "is 240 at least 150?" —true.${...}puts theboolanswer straight into the message.
Example 8 — Shopping Budget
void main() {
int price = 450;
int quantity = 3;
int budget = 1200;
int total = price * quantity;
print('Total: $total');
print('Within budget: ${total <= budget}');
print('Exactly on budget: ${total == budget}');
}Total: 1350
Within budget: false
Exactly on budget: falseHow it works
450 * 3is1350.1350 <= 1200isfalse— Sara is over budget.<=(not<) is used, so spending exactly1200would still count as within budget.
Example 9 — Bank Balance
void main() {
double balance = 500.0;
double withdrawal = 500;
bool canWithdraw = withdrawal <= balance;
print('Can withdraw: $canWithdraw');
balance = balance - withdrawal;
print('Balance: $balance');
print('Account empty: ${balance == 0}');
}Can withdraw: true
Balance: 0.0
Account empty: trueHow it works
500 <= 500.0istrue— withdrawing the whole balance is allowed.- After the subtraction,
balanceis0.0. balance == 0compares adoublewith anint;0.0and0are equal values, sotrue.
Example 10 — Temperature Check
void main() {
double celsius = 36.6;
double fahrenheit = celsius * 9 / 5 + 32;
print('Fahrenheit: $fahrenheit');
print('Exactly 97.88: ${fahrenheit == 97.88}');
print('Close to 97.88: ${(fahrenheit - 97.88).abs() < 0.001}');
print('Fever: ${celsius > 37.5}');
}Fahrenheit: 97.88000000000001
Exactly 97.88: false
Close to 97.88: true
Fever: falseHow it works
- The calculation produces
97.88000000000001— the tinydoubleerror from Lecture 009. - So
==with97.88isfalse, even though the answer is "really"97.88. - Checking that the difference is smaller than
0.001gives the sensible answer,true. 36.6 > 37.5isfalse: no fever.
Common Beginner Mistakes
1. Using = instead of ==
void main() {
int a = 1;
int b = 2;
bool same = a = b; // ✗ assigns, does not compare
}Error: A value of type 'int' can't be assigned to a variable of type 'bool'.
bool same = a = b;
^a = b puts 2 into a. Write a == b to compare.
2. Writing =< or => instead of <= or >=
void main() {
print(5 =< 6); // ✗
}Error: Expected a type, but got '6'.
print(5 =< 6);
^Dart prints several confusing errors after this one. The rule: the = always comes
second — <=, >=, !=.
3. Chaining comparisons
void main() {
int age = 25;
print(18 < age < 60); // ✗
}Error: A comparison expression can't be an operand of another comparison expression.Compare one pair at a time. Combining questions comes in Lecture 019.
4. Using < or > on strings
void main() {
print('apple' < 'banana'); // ✗
}Error: The operator '<' isn't defined for the type 'String'.5. Using > on a nullable value
void main() {
int? score;
print(score > 5); // ✗
}Error: Operator '>' cannot be called on 'int?' because it is potentially null.Use (score ?? 0) > 5, or check score != null first.
6. Comparing a string with a number
'20' == 20 is false with no error at all. Convert with int.parse() before comparing.
7. Expecting calculated decimals to be exactly equal
0.1 + 0.2 == 0.3 is false. Compare calculated double values with a small tolerance.
8. Forgetting capitals and spaces
'Ali' == 'ali' and 'Ali' == 'Ali ' are both false. Use trim() and toLowerCase()
on text people type.
Best Practices
- Store important comparisons in
boolvariables with clear names:hasPassed,isOverBudget,canWithdraw. - Decide carefully between
>and>=— ask what should happen exactly at the boundary. - Compare values of the same type; convert text to numbers first.
- Never use
==on calculateddoublevalues; check the difference is tiny instead. - Normalize text with
trim()andtoLowerCase()before comparing what people type. - Write
isMember, notisMember == true— aboolis already the answer. - Use
==for everyday equality; reach foridentical()only when you truly mean "the same object".
Mini Challenge
Ali typed ' ALI ' as his username, and his saved username is 'ali'. His account balance
is 250 and he wants to buy a book costing 300. Print whether the username matches
(ignoring spaces and capitals) and whether he can afford the book.
Your program should print exactly:
Username matches: true
Can afford: falseTry it yourself before opening the solution.
Show solution
void main() {
String typed = ' ALI ';
String saved = 'ali';
int balance = 250;
int bookPrice = 300;
bool usernameMatches = typed.trim().toLowerCase() == saved;
bool canAfford = balance >= bookPrice;
print('Username matches: $usernameMatches');
print('Can afford: $canAfford');
}Username matches: true
Can afford: falseHow it works
trim()removes the spaces andtoLowerCase()turnsALIintoali, so==istrue.250 >= 300isfalse— Ali needs50more.
Practice Questions
Work through these in order — they run from beginner to application to challenge. Every question gives you exact values, so you can compare your output with the answers.
Beginner
- Print whether
10is equal to10.0. - Store
a = 7andb = 12. Printa < b,a >= b, anda != b, each on its own line. - Print whether
'Dart'is equal to'dart'.
Application
- Store
marks = 49andpassMark = 50. Store whether the student passed in aboolnamedhasPassed, then printPassed: false. - Store
typed = ' Sara 'andsaved = 'sara'. Print whether they match after removing spaces and ignoring capitals. - Store
price = 1200andbudget = 1000. PrintWithin budget: …using<=. - Declare
String? middleName;with no value. PrintHas middle name: …using!=. - Store
age = 18. PrintAdult: …(age is 18 or more) andExactly 18: ….
Challenge
- Calculate
0.1 * 3and store it inresult. Printresult, then print whether it is exactly equal to0.3, then whether it is within0.000001of0.3. - Store
String typedPin = '1234',int savedPin = 1234, andint? lastDeposit;(no value). PrintPIN correct: …(convert the typed PIN first),Has deposit: …, andBig deposit: …(whether the deposit, treatingnullas0, is more than100).
Practice Answers
Question 1 — Solution
void main() {
print(10 == 10.0);
}trueQuestion 2 — Solution
void main() {
int a = 7;
int b = 12;
print(a < b);
print(a >= b);
print(a != b);
}true
false
trueQuestion 3 — Solution
void main() {
print('Dart' == 'dart');
}falseCapital D and small d are different characters.
Question 4 — Solution
void main() {
int marks = 49;
int passMark = 50;
bool hasPassed = marks >= passMark;
print('Passed: $hasPassed');
}Passed: falseQuestion 5 — Solution
void main() {
String typed = ' Sara ';
String saved = 'sara';
print(typed.trim().toLowerCase() == saved);
}trueQuestion 6 — Solution
void main() {
int price = 1200;
int budget = 1000;
print('Within budget: ${price <= budget}');
}Within budget: falseQuestion 7 — Solution
void main() {
String? middleName;
print('Has middle name: ${middleName != null}');
}Has middle name: falseQuestion 8 — Solution
void main() {
int age = 18;
print('Adult: ${age >= 18}');
print('Exactly 18: ${age == 18}');
}Adult: true
Exactly 18: trueage > 18 would wrongly say false here — the boundary matters.
Question 9 — Solution
void main() {
double result = 0.1 * 3;
print(result);
print(result == 0.3);
print((result - 0.3).abs() < 0.000001);
}0.30000000000000004
false
trueQuestion 10 — Solution
void main() {
String typedPin = '1234';
int savedPin = 1234;
int? lastDeposit;
print('PIN correct: ${int.parse(typedPin) == savedPin}');
print('Has deposit: ${lastDeposit != null}');
print('Big deposit: ${(lastDeposit ?? 0) > 100}');
}PIN correct: true
Has deposit: false
Big deposit: falseWithout int.parse(), typedPin == savedPin would compare a String with an int and
quietly give false. Without ?? 0, lastDeposit > 100 would not compile.
Quick Revision
- What type of value does every comparison produce?
- What is the difference between
=and==? - When do
>and>=give different answers? - Why is
1 == 1.0true? - Why is
0.1 + 0.2 == 0.3false, and what should you do instead? - Why is
'Ali' == 'ali'false? - Which comparison operators work on a nullable variable without a default?
- Why does
18 < age < 60not compile? - What does
identical()check that==does not?
Key Takeaways
- A comparison asks a yes-or-no question and produces a
bool:trueorfalse. - The six operators are
==,!=,>,<,>=, and<=;=assigns,==compares. >and>=differ only at the boundary — choose deliberately.intanddoublecompare by value:1 == 1.0istrue.- Calculated
doublevalues should be compared with a small tolerance, not==. - Strings are equal only when every character matches; they have no
<or>. - Values of different types, like
'20'and20, are never equal — convert first. == nulland!= nullcheck nullable values;>,<,>=,<=need a real value.identical()checks for the same object; use==for everyday equality.
What's Next?
Lecture 19 — Logical Operators. Each comparison in this lecture answered one question.
But real decisions often depend on several at once: is the age at least 18 and under
60? Is the user an admin or the owner? Next we will learn &&, ||, and !, which
combine and flip bool values — and finally write that age check properly.