Search code examples
javabigintegermodular

The Weird BigInteger.mod Modulus Method


In Java, we know if we want to compare two reference objects, we usually need to use equals, but here I am so confused about the output of the following:

System.out.println(new BigInteger("0") == BigInteger.ZERO);                     // false
System.out.println(new BigInteger("0").mod(BigInteger.ONE) == BigInteger.ZERO); // true

Why is the second statement true?


Solution

  • Took a while, but following the logical paths of the execution takes us to:

    MutableBigInteger#toBigInteger(int sign)

    Which has the following statement:

    BigInteger toBigInteger(int sign) {
        if (intLen == 0 || sign == 0)
            return BigInteger.ZERO;
        return new BigInteger(getMagnitudeArray(), sign);
    }
    

    So in this case, the constant BigInteger.ZERO is returned, so the statement is true.

    Stack trace:

    BigInteger#mod(BigInteger)
    BigInteger#remainder(BigInteger)
    BigInteger#remainderKnuth(BigInteger)
    MutableBigInteger#toBigInteger(int)