Java – Comparing BigInteger Values

java

BigInteger bigInteger = ...;


if(bigInteger.longValue() > 0) {  //original code
    //bigger than 0
}

//should I change to this?
if(bigInteger.compareTo(BigInteger.valueOf(0)) == 1) {
    //bigger than 0
}

I need to compare some arbitary BigInteger values. I wonder which approach is correct. Given the above code which one should be used? The original code is on the top.. I am thinking to change it to the second approach.

Best Answer

The first approach is wrong if you want to test if the BigInteger has a postive value: longValue just returns the low-order 64 bit which may revert the sign... So the test could fail for a positive BigInteger.

The second approach is better (see Bozhos answer for an optimization).

Another alternative: BigInteger#signum returns 1 if the value is positive:

if (bigInteger.signum() == 1) {
 // bigger than 0
}
Related Question