Watch the video (9 min)
On this page28 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What Is a Comparison?
  5. 2. The Six Comparison Operators
  6. 3. == and !=
  7. 4. Greater Than and Less Than
  8. 5. The "Or Equal" Operators
  9. 6. Storing the Result
  10. 7. Comparing int and double
  11. 8. The double Trap
  12. 9. Comparing Strings
  13. 10. Strings Have No < or >
  14. 11. Comparing bool Values
  15. 12. Comparing Different Types
  16. 13. Comparing with null
  17. 14. One Comparison at a Time
  18. 15. identical() — The Same Object?
  19. 16. A Real-World Example
  20. Code Examples
  21. Common Beginner Mistakes
  22. Best Practices
  23. Mini Challenge
  24. Practice Questions
  25. Practice Answers
  26. Quick Revision
  27. Key Takeaways
  28. What's Next?

Lecture 18 — Comparison & Equality

Category4 — Operators
Lecture018 of 140
Estimated video length9 min
TargetDart 3.12.2
LevelBeginner

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 true or false.

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 types int, double, String, and bool
  • string interpolation with $name and ${...}
  • string methods such as toLowerCase() and trim(), and length
  • number methods such as abs(), and why 0.1 + 0.2 is not exactly 0.3
  • int.parse() and runtimeType
  • nullable types (int?, String?) and the ?? operator
  • arithmetic and assignment operators

Connection With Previous Lectures

In Lecture 017 we learned to calculate:

dart
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 bool value
  • Use the six comparison operators: ==, !=, >, <, >=, and <=
  • Store the result of a comparison in a bool variable
  • Compare int and double values, and explain why 1 == 1.0 is true
  • 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.

dart
void main() {
  print(10 > 5);
  print(3 > 8);
}
output
true
false

10 > 5 asks "is 10 greater than 5?" — yes, so true.


2. The Six Comparison Operators

OperatorQuestion it asksExampleResult
==equal to?5 == 5true
!=not equal to?5 != 5false
>greater than?7 > 3true
<less than?7 < 3false
>=greater than or equal to?5 >= 5true
<=less than or equal to?4 <= 5true

== 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.

dart
void main() {
  int a = 20;
  int b = 20;
  print(a == b);
  print(a != b);
}
output
true
false

Remember from Lecture 004: a single = assigns a value. Only == compares.


4. Greater Than and Less Than

dart
void main() {
  int aliAge = 20;
  int saraAge = 18;
  print(aliAge > saraAge);
  print(aliAge < saraAge);
}
output
true
false

Read 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.

dart
void main() {
  int marks = 50;
  print(marks > 50);
  print(marks >= 50);
  print(marks <= 50);
}
output
false
true
true

If 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.

dart
void main() {
  int marks = 72;
  int passMark = 50;
  bool hasPassed = marks >= passMark;
  print('Passed: $hasPassed');
}
output
Passed: true

In 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.

dart
void main() {
  print(1 == 1.0);
  print(10 > 9.5);
  print(5 >= 5.0);
}
output
true
true
true

1 and 1.0 are the same number, so == says true — even though their types differ:

dart
void main() {
  print(1.runtimeType == 1.0.runtimeType);
}
output
false

The 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:

dart
void main() {
  double sum = 0.1 + 0.2;
  print(sum);
  print(sum == 0.3);
}
output
0.30000000000000004
false

For calculated decimals, ask "are they close enough?" instead: the difference, made positive with abs(), should be tiny.

dart
void main() {
  double sum = 0.1 + 0.2;
  print((sum - 0.3).abs() < 0.000001);
}
output
true

9. Comparing Strings

== works on strings too. Two strings are equal only if they contain exactly the same characters, in the same order.

dart
void main() {
  print('Ali' == 'Ali');
  print('Ali' == 'ali');
  print('Ali' == 'Ali ');
}
output
true
false
false

A capital letter or a trailing space makes them different. When people type text, clean both sides first with trim() and toLowerCase():

dart
void main() {
  String typed = '  SARA ';
  String saved = 'sara';
  print(typed.trim().toLowerCase() == saved);
}
output
true

10. Strings Have No < or >

>, <, >=, and <= are for numbers. Using them on strings is an error:

dart
void main() {
  print('apple' < 'banana'); // ✗
}
output
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:

dart
void main() {
  String password = 'dart2026';
  print(password.length >= 8);
}
output
true

Putting text in alphabetical order comes later, in Lecture 045 — Sorting & Reversing Lists.


11. Comparing bool Values

bool values support == and !=, but not < or >.

dart
void main() {
  bool aliPaid = true;
  bool saraPaid = false;
  print(aliPaid == saraPaid);
  print(aliPaid != saraPaid);
}
output
false
true

true > 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:

dart
void main() {
  String typedAge = '20';
  int realAge = 20;
  print(typedAge == realAge);
  print(int.parse(typedAge) == realAge);
}
output
false
true

There 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:

dart
void main() {
  String? middleName;
  int? score = 0;
  print(middleName == null);
  print(score != null);
}
output
true
true

0 is a real value, not null.

About the editor warning. In a tiny program like this, Dart can see that middleName was never given a value, so dart analyze warns The 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:

dart
void main() {
  int? score;
  print(score > 5); // ✗
}
output
Error: Operator '>' cannot be called on 'int?' because it is potentially null.
  print(score > 5);
              ^

Give it a default first with ?? from Lecture 014:

dart
void main() {
  int? score;
  print((score ?? 0) > 5);
}
output
false

14. One Comparison at a Time

In mathematics you might write 18 < age < 60. Dart does not allow that:

dart
void main() {
  int age = 25;
  print(18 < age < 60); // ✗
}
output
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?"

dart
void main() {
  String a = 'ali';
  String b = 'ALI'.toLowerCase();
  print(a == b);
  print(identical(a, b));
}
output
true
false

Both 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

dart
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');
}
output
Student: Zayan
Passed: true
Top score: false
Has bonus: false
Reached 80: false

Each 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

dart
void main() {
  int x = 15;
  int y = 20;
  print(x == y);
  print(x != y);
}
output
false
true

Example 2 — All Four Relational Operators

dart
void main() {
  int a = 9;
  int b = 4;
  print(a > b);
  print(a < b);
  print(a >= b);
  print(a <= b);
}
output
true
false
true
false

Example 3 — The Boundary

dart
void main() {
  int speed = 60;
  int limit = 60;
  print('Over the limit: ${speed > limit}');
  print('At or under the limit: ${speed <= limit}');
}
output
Over the limit: false
At or under the limit: true

Example 4 — int Meets double

dart
void main() {
  int whole = 3;
  double decimal = 3.0;
  print(whole == decimal);
  print(whole < 3.5);
}
output
true
true

Example 5 — Comparing Text Fairly

dart
void main() {
  String answer = ' Dart ';
  print(answer == 'dart');
  print(answer.trim().toLowerCase() == 'dart');
}
output
false
true

Example 6 — Checking for null

dart
void main() {
  String? nickname;
  String? city = 'Lahore';
  print(nickname == null);
  print(city != null);
}
output
true
true

Example 7 — Student Pass Check

dart
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}');
}
output
Student: Ali
Total: 240
Passed: true

How it works

  1. total is calculated first: 80 + 75 + 85 is 240.
  2. total >= passTotal asks "is 240 at least 150?" — true.
  3. ${...} puts the bool answer straight into the message.

Example 8 — Shopping Budget

dart
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}');
}
output
Total: 1350
Within budget: false
Exactly on budget: false

How it works

  1. 450 * 3 is 1350.
  2. 1350 <= 1200 is false — Sara is over budget.
  3. <= (not <) is used, so spending exactly 1200 would still count as within budget.

Example 9 — Bank Balance

dart
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}');
}
output
Can withdraw: true
Balance: 0.0
Account empty: true

How it works

  1. 500 <= 500.0 is true — withdrawing the whole balance is allowed.
  2. After the subtraction, balance is 0.0.
  3. balance == 0 compares a double with an int; 0.0 and 0 are equal values, so true.

Example 10 — Temperature Check

dart
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}');
}
output
Fahrenheit: 97.88000000000001
Exactly 97.88: false
Close to 97.88: true
Fever: false

How it works

  1. The calculation produces 97.88000000000001 — the tiny double error from Lecture 009.
  2. So == with 97.88 is false, even though the answer is "really" 97.88.
  3. Checking that the difference is smaller than 0.001 gives the sensible answer, true.
  4. 36.6 > 37.5 is false: no fever.

Common Beginner Mistakes

1. Using = instead of ==

dart
void main() {
  int a = 1;
  int b = 2;
  bool same = a = b; // ✗ assigns, does not compare
}
output
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 >=

dart
void main() {
  print(5 =< 6); // ✗
}
output
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

dart
void main() {
  int age = 25;
  print(18 < age < 60); // ✗
}
output
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

dart
void main() {
  print('apple' < 'banana'); // ✗
}
output
Error: The operator '<' isn't defined for the type 'String'.

5. Using > on a nullable value

dart
void main() {
  int? score;
  print(score > 5); // ✗
}
output
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 bool variables 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 calculated double values; check the difference is tiny instead.
  • Normalize text with trim() and toLowerCase() before comparing what people type.
  • Write isMember, not isMember == true — a bool is already the answer.
  • Use == for everyday equality; reach for identical() 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:

output
Username matches: true
Can afford: false

Try it yourself before opening the solution.

Show solution
dart
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');
}
output
Username matches: true
Can afford: false

How it works

  1. trim() removes the spaces and toLowerCase() turns ALI into ali, so == is true.
  2. 250 >= 300 is false — Ali needs 50 more.

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

  1. Print whether 10 is equal to 10.0.
  2. Store a = 7 and b = 12. Print a < b, a >= b, and a != b, each on its own line.
  3. Print whether 'Dart' is equal to 'dart'.

Application

  1. Store marks = 49 and passMark = 50. Store whether the student passed in a bool named hasPassed, then print Passed: false.
  2. Store typed = ' Sara ' and saved = 'sara'. Print whether they match after removing spaces and ignoring capitals.
  3. Store price = 1200 and budget = 1000. Print Within budget: … using <=.
  4. Declare String? middleName; with no value. Print Has middle name: … using !=.
  5. Store age = 18. Print Adult: … (age is 18 or more) and Exactly 18: ….

Challenge

  1. Calculate 0.1 * 3 and store it in result. Print result, then print whether it is exactly equal to 0.3, then whether it is within 0.000001 of 0.3.
  2. Store String typedPin = '1234', int savedPin = 1234, and int? lastDeposit; (no value). Print PIN correct: … (convert the typed PIN first), Has deposit: …, and Big deposit: … (whether the deposit, treating null as 0, is more than 100).

Practice Answers

Question 1 — Solution

dart
void main() {
  print(10 == 10.0);
}
output
true

Question 2 — Solution

dart
void main() {
  int a = 7;
  int b = 12;
  print(a < b);
  print(a >= b);
  print(a != b);
}
output
true
false
true

Question 3 — Solution

dart
void main() {
  print('Dart' == 'dart');
}
output
false

Capital D and small d are different characters.

Question 4 — Solution

dart
void main() {
  int marks = 49;
  int passMark = 50;
  bool hasPassed = marks >= passMark;
  print('Passed: $hasPassed');
}
output
Passed: false

Question 5 — Solution

dart
void main() {
  String typed = ' Sara ';
  String saved = 'sara';
  print(typed.trim().toLowerCase() == saved);
}
output
true

Question 6 — Solution

dart
void main() {
  int price = 1200;
  int budget = 1000;
  print('Within budget: ${price <= budget}');
}
output
Within budget: false

Question 7 — Solution

dart
void main() {
  String? middleName;
  print('Has middle name: ${middleName != null}');
}
output
Has middle name: false

Question 8 — Solution

dart
void main() {
  int age = 18;
  print('Adult: ${age >= 18}');
  print('Exactly 18: ${age == 18}');
}
output
Adult: true
Exactly 18: true

age > 18 would wrongly say false here — the boundary matters.

Question 9 — Solution

dart
void main() {
  double result = 0.1 * 3;
  print(result);
  print(result == 0.3);
  print((result - 0.3).abs() < 0.000001);
}
output
0.30000000000000004
false
true

Question 10 — Solution

dart
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}');
}
output
PIN correct: true
Has deposit: false
Big deposit: false

Without int.parse(), typedPin == savedPin would compare a String with an int and quietly give false. Without ?? 0, lastDeposit > 100 would not compile.


Quick Revision

  1. What type of value does every comparison produce?
  2. What is the difference between = and ==?
  3. When do > and >= give different answers?
  4. Why is 1 == 1.0 true?
  5. Why is 0.1 + 0.2 == 0.3 false, and what should you do instead?
  6. Why is 'Ali' == 'ali' false?
  7. Which comparison operators work on a nullable variable without a default?
  8. Why does 18 < age < 60 not compile?
  9. What does identical() check that == does not?

Key Takeaways

  • A comparison asks a yes-or-no question and produces a bool: true or false.
  • The six operators are ==, !=, >, <, >=, and <=; = assigns, == compares.
  • > and >= differ only at the boundary — choose deliberately.
  • int and double compare by value: 1 == 1.0 is true.
  • Calculated double values 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' and 20, are never equal — convert first.
  • == null and != null check 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.


Video lecture

Subscribe
Placeholder video — the real recording isn't linked yet.