The `compareTo` method in Dart compares this integer to another number.
The syntax of int.compareTo() method is:
int compareTo(num other)
This compareTo() method of int compares this to other.
Parameter | Optional/Required | Description |
---|---|---|
other | required | The number to compare to. |
int.compareTo() returns value of type int
.
In this example,
5
and 3
to the integer variables num1
and num2
respectively.num1
to num2
using the compareTo()
method.void main() {
int num1 = 5;
int num2 = 3;
int comparison = num1.compareTo(num2);
print('Comparison result: $comparison');
}
Comparison result: 1
In this example,
10
and 20
to the integer variables num1
and num2
respectively.num1
to num2
using the compareTo()
method.void main() {
int num1 = 10;
int num2 = 20;
int comparison = num1.compareTo(num2);
print('Comparison result: $comparison');
}
Comparison result: -1
In this example,
-3
and -5
to the integer variables num1
and num2
respectively.num1
to num2
using the compareTo()
method.void main() {
int num1 = -3;
int num2 = -5;
int comparison = num1.compareTo(num2);
print('Comparison result: $comparison');
}
Comparison result: 1
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.