Comparing BigIntegers

suggest change

You 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.

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:

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.
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents