Dart int compareTo()
Syntax & Examples

int.compareTo() method

The `compareTo` method in Dart compares this integer to another number.


Syntax of int.compareTo()

The syntax of int.compareTo() method is:

 int compareTo(num other) 

This compareTo() method of int compares this to other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredThe number to compare to.

Return Type

int.compareTo() returns value of type int.



✐ Examples

1 Compare two positive integers

In this example,

  1. We assign the values 5 and 3 to the integer variables num1 and num2 respectively.
  2. We compare num1 to num2 using the compareTo() method.
  3. We print the result to standard output.

Dart Program

void main() {
  int num1 = 5;
  int num2 = 3;
  int comparison = num1.compareTo(num2);
  print('Comparison result: $comparison');
}

Output

Comparison result: 1

2 Compare two positive integers

In this example,

  1. We assign the values 10 and 20 to the integer variables num1 and num2 respectively.
  2. We compare num1 to num2 using the compareTo() method.
  3. We print the result to standard output.

Dart Program

void main() {
  int num1 = 10;
  int num2 = 20;
  int comparison = num1.compareTo(num2);
  print('Comparison result: $comparison');
}

Output

Comparison result: -1

3 Compare two negative integers

In this example,

  1. We assign the values -3 and -5 to the integer variables num1 and num2 respectively.
  2. We compare num1 to num2 using the compareTo() method.
  3. We print the result to standard output.

Dart Program

void main() {
  int num1 = -3;
  int num2 = -5;
  int comparison = num1.compareTo(num2);
  print('Comparison result: $comparison');
}

Output

Comparison result: 1

Summary

In this Dart tutorial, we learned about compareTo() method of int: the syntax and few working examples with output and detailed explanation for each example.