Java Compare BigInteger values for equality

Tags: BigInteger BigInteger equals

In this Java core tutorial we learn how to compare BigInteger values for equality using the java.math.BigInteger.equals() method.

How to compare BigInteger values for equality

To compare two BigInteger values for equality we can use the java.math.BigInteger.equals() method as the following Java example program.

EqualBigIntegerExample.java

import java.math.BigInteger;

public class EqualBigIntegerExample {
    public static void main(String... args) {
        BigInteger value1 = new BigInteger("1234567890987654321");
        BigInteger value2 = new BigInteger("1234567890987654322");
        BigInteger value3 = new BigInteger("1234567890987654322");

        boolean result1 = value1.equals(value2);
        boolean result2 = value1.equals(value3);
        boolean result3 = value2.equals(value3);

        System.out.println(value1 + " equal " + value2 + ": " + result1);
        System.out.println(value1 + " equal " + value3 + ": " + result2);
        System.out.println(value2 + " equal " + value3 + ": " + result3);
    }
}
The output is:
1234567890987654321 equal 1234567890987654322: false
1234567890987654321 equal 1234567890987654322: false
1234567890987654322 equal 1234567890987654322: true

Happy Coding 😊