Search code examples
javaintbigint

Why i can't use equals for BigInteger and int?


When i try to compare BigInteger and int:

 BigInteger balance = new BigInteger(out_str.substring(186, 201).trim());
 if (!balance.equals(0)) {...}

I get:

equals () between objects of inconvertible types 'int' and 'BigInteger'


Solution

  • int and BigInteger don't share any class as int is a primitive type.

    You can only compare stuff which has at least something in common, like Object. So a comparison like BigInteger with the wrapper class Integer would compile, but the result would be false since an Integer is no BigInteger. You will need to transform your int to a BigInteger for comparison.

    For 0 there is the constant BigInteger.ZERO (documentation):

    if (!balance.equals(BigInteger.ZERO)) {
        ...
    }