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
Parameter | Optional/Required | Description |
---|---|---|
other | required | The number to compare to. |
Return Type
int.compareTo() returns value of type int
.
✐ Examples
1 Compare two positive integers
In this example,
- We assign the values
5
and3
to the integer variablesnum1
andnum2
respectively. - We compare
num1
tonum2
using thecompareTo()
method. - 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,
- We assign the values
10
and20
to the integer variablesnum1
andnum2
respectively. - We compare
num1
tonum2
using thecompareTo()
method. - 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,
- We assign the values
-3
and-5
to the integer variablesnum1
andnum2
respectively. - We compare
num1
tonum2
using thecompareTo()
method. - 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.