Dart Relational Operators


Relational operators in Dart are used to compare two values or expressions. These operators return a boolean value (true or false) based on the outcome of the comparison. Relational operators are essential for making decisions in your code, such as in conditional statements and loops.

Overview of Relational Operators

Here’s a list of relational operators available in Dart:

  1. Equal to (==)
  2. Not equal to (!=)
  3. Greater than (>)
  4. Less than (<)
  5. Greater than or equal to (>=)
  6. Less than or equal to (<=)

1. Equal to (==)

  • Description: Checks if two values are equal.
  • Usage: Returns true if the values are equal, otherwise false.

Example:

void main() { int a = 5; int b = 5; print('Is a equal to b? ${a == b}'); // Output: true }

2. Not equal to (!=)

  • Description: Checks if two values are not equal.
  • Usage: Returns true if the values are not equal, otherwise false.

Example:

void main() { int a = 5; int b = 3; print('Is a not equal to b? ${a != b}'); // Output: true }

3. Greater than (>)

  • Description: Checks if the left operand is greater than the right operand.
  • Usage: Returns true if the left operand is greater, otherwise false.

Example:

void main() { int a = 5; int b = 3; print('Is a greater than b? ${a > b}'); // Output: true }

4. Less than (<)

  • Description: Checks if the left operand is less than the right operand.
  • Usage: Returns true if the left operand is less, otherwise false.

Example:

void main() { int a = 5; int b = 8; print('Is a less than b? ${a < b}'); // Output: true }

5. Greater than or equal to (>=)

  • Description: Checks if the left operand is greater than or equal to the right operand.
  • Usage: Returns true if the left operand is greater or equal, otherwise false.

Example:

void main() { int a = 5; int b = 5; print('Is a greater than or equal to b? ${a >= b}'); // Output: true }

6. Less than or equal to (<=)

  • Description: Checks if the left operand is less than or equal to the right operand.
  • Usage: Returns true if the left operand is less or equal, otherwise false.

Example:

void main() { int a = 3; int b = 5; print('Is a less than or equal to b? ${a <= b}'); // Output: true }

Summary of Relational Operators

OperatorDescriptionExample
==Equal to5 == 5 (results in true)
!=Not equal to5 != 3 (results in true)
>Greater than5 > 3 (results in true)
<Less than5 < 8 (results in true)
>=Greater than or equal to5 >= 5 (results in true)
<=Less than or equal to3 <= 5 (results in true)

Conclusion

Relational operators in Dart are crucial for comparing values and controlling the flow of your program. They help in decision-making processes, such as within if statements, loops, and while filtering data. Understanding how to use relational operators effectively allows you to write more dynamic and responsive Dart applications.