Java Language Comparing BigIntegers


Example

You can compare BigIntegers same as 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");
}

Output:

Not Equal

Note:

In general, do not use use the == operator to compare BigIntegers

  • == operator: compares references; i.e. whether two values refer to the same object
  • equals() 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 BigIntegers contain the same content, but do not refer to the same object, this will fail. Instead, compare BigIntegers using the equals methods, as explained above.

You can also compare your BigInteger to constant values like 0,1,10.

for example:

BigInteger reallyBig = BigInteger.valueOf(1);
if(BigInteger.ONE.equals(reallyBig)){
    //code when they are equal.
}    

You can also compare two BigIntegers by using compareTo() method, as following: compareTo() returns 3 values.

  • 0: When both are equal.
  • 1: When first is greater than second (the one in brackets).
  • -1: When first is less than second.
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) == 1){
    //code when reallyBig is greater than reallyBig1.
}
else if(reallyBig.compareTo(reallyBig1) == -1){
    //code when reallyBig is less than reallyBig1.
}