2

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?

Peter Lee
  • 12,931
  • 11
  • 73
  • 100

2 Answers2

5

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)
Obicere
  • 2,999
  • 3
  • 20
  • 31
0

Its a three method implementation :

public BigInteger mod(BigInteger m) {
if (m.signum <= 0)
    throw new ArithmeticException("BigInteger: modulus not positive");

BigInteger result = this.remainder(m);     // call remainder()
return (result.signum >= 0 ? result : result.add(m));  
}



public BigInteger remainder(BigInteger val) {
    MutableBigInteger q = new MutableBigInteger(),
                      a = new MutableBigInteger(this.mag),
                      b = new MutableBigInteger(val.mag);

    return a.divide(b, q).toBigInteger(this.signum); // call toBigInteger()
}



BigInteger toBigInteger(int sign) {
    if (intLen == 0 || sign == 0)
        return BigInteger.ZERO;    // here is your answer.
    return new BigInteger(getMagnitudeArray(), sign);
}
TheLostMind
  • 35,966
  • 12
  • 68
  • 104