Comparing BigIntegers
suggest changeYou can compare BigInteger values the same way you compare String or other objects in Java.
For example:
BigInteger one = BigInteger.valueOf(1);
BigInteger two = BigInteger.valueOf(2);
if(one.equals(two)){
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
Not Equal
Note:
In general, do not use the == operator to compare BigInteger values.
==operator: compares references; i.e. whether two values refer to the same objectequals()method: compares the content of two BigIntegers.
For example, BigIntegers should not be compared in the following way:
if (firstBigInteger == secondBigInteger) {
// Only checks for reference equality, not content equality!
}
Doing so may lead to unexpected behavior, as the == operator only checks for reference equality. If both BigInteger values contain the same content, but do not refer to the same object, this comparison is false. Instead, compare them with equals, as explained above.
You can also compare a BigInteger to a constant such as BigInteger.ZERO, BigInteger.ONE, or BigInteger.TEN.
For example:
BigInteger reallyBig = BigInteger.valueOf(1);
if(BigInteger.ONE.equals(reallyBig)){
//code when they are equal.
}
You can also compare two BigInteger values with compareTo(). It returns a negative integer, zero, or a positive integer, not necessarily -1 or 1:
- 0 when the two values are equal.
- A positive value when the receiver is greater than the argument.
- A negative value when the receiver is less than the argument.
BigInteger reallyBig = BigInteger.valueOf(10);
BigInteger reallyBig1 = BigInteger.valueOf(100);
if (reallyBig.compareTo(reallyBig1) == 0) {
//code when both are equal.
}
else if (reallyBig.compareTo(reallyBig1) > 0) {
//code when reallyBig is greater than reallyBig1.
}
else {
//code when reallyBig is less than reallyBig1.
}