Comparing BigIntegers

suggest change

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);

    System.out.println("Not Equal");


Not Equal


In general, do not use use the == operator to compare 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);
    //code when they are equal.

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

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.

Feedback about page:

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

Table Of Contents