Java compare BigInteger values
Tags: BigInteger BigInteger compareTo
In this Java core tutorial we learn how to use the java.math.BigInteger.compareTo() method to compare two BigInteger objects.
How to compare BigInteger values
To compare two BigInteger values we can use the java.math.BigInteger.compareTo() method which returns -1, 0 or 1 as the result of comparison less than, equal to or greater than.
CompareBigIntegerExample.java
import java.math.BigInteger;
public class CompareBigIntegerExample {
public static void main(String... args) {
BigInteger value1 = new BigInteger("1234567890987654321");
BigInteger value2 = new BigInteger("1234567890987654322");
BigInteger value3 = new BigInteger("1234567890987654322");
int result1 = value1.compareTo(value2);
int result2 = value3.compareTo(value1);
int result3 = value2.compareTo(value3);
System.out.println(value1 + " compare to " + value2 + ": " + result1);
System.out.println(value3 + " compare to " + value1 + ": " + result2);
System.out.println(value2 + " compare to " + value3 + ": " + result3);
}
}
1234567890987654321 compare to 1234567890987654322: -1
1234567890987654322 compare to 1234567890987654321: 1
1234567890987654322 compare to 1234567890987654322: 0
Happy Coding 😊