Lesson 10 min
Relational & Equality Operators
00:00 / 00:00
Relational & Equality Operators
Relational and equality operators are used to compare two values. In Dart, all these operators return a boolean value (true or false).
List of Operators
| Operator | Description | Example |
|---|---|---|
== | Equal to | 5 == 5 // true |
!= | Not equal to | 5 != 3 // true |
> | Greater than | 5 > 3 // true |
< | Less than | 5 < 3 // false |
>= | Greater than or equal to | 5 >= 5 // true |
<= | Less than or equal to | 3 <= 5 // true |
Key Concepts and Examples
1. Basic Comparisons
Relational operators work directly on numbers and strings.
dartvoid main() { int speed = 80; bool isSpeeding = speed > 70; print("Is Speeding: $isSpeeding"); // true String category = "electronics"; bool isMatch = category == "electronics"; print("Is Match: $isMatch"); // true }
2. No Triple Equals (===) in Dart
Unlike JavaScript, Dart does not have a === (strict equality) operator. Because Dart is strongly typed, comparing two variables of different types (like int and String) with == will generate a compile-time warning or error.
dartvoid main() { // Dart enforces type check. You cannot compare unrelated types directly. int numVal = 5; String strVal = "5"; // print(numVal == strVal); // Warning/Compile error in strict mode }
3. Structural vs Referential Equality
By default, the == operator checks for structural equality or value equality for primitive types. For user-defined class objects, == defaults to referential identity (checking if they point to the exact same location in memory).
To check if two objects point to the same memory reference, you can use the global identical() function.
dartclass Person { final String name; Person(this.name); } void main() { var p1 = Person("John"); var p2 = Person("John"); print(p1 == p2); // false (Different memory locations) print(identical(p1, p2)); // false var p3 = p1; print(identical(p1, p3)); // true (Same instance) }
Summary
- Relational operators are used in conditional expressions (
if,while) to make decisions. - There is no triple equals (
===) in Dart; type safety prevents mismatched comparisons. - Use
identical()to test if two variables reference the exact same object in memory.