How to check if a BigInteger is null

20.7k views Asked by At

I have a code which may assign null to a BigInteger. I need to check if it is null or not.

I've tried the following things, and they do not work:

  1. == will just check the reference, not the value.

    BigInteger x = BigInteger.ONE;
    
    if(x== null)
    {
        System.out.println( x );
    }
    

Output of above is it prints x. (Somehow the boolean condition is satisfied, even though x is not null).

  1. Following gives NullPointerException upon comparing

    BigInteger x = BigInteger.ONE;
    BigInteger myNull = null;
    
    if(x.compareTo(myNull) == 0 )
    {
        System.out.println( x );
    }
    
  2. Another NPE:

    BigInteger x = BigInteger.ONE;
    
    if(x.compareTo(null) == 0)
    {
        System.out.println( x );
    }
    

How do I check if a BigInteger is null properly?

2

There are 2 answers

0
Bathsheba On

.compareTo(arg) throws a NullPointerException if arg is null.

You should check if arg is null prior to calling the method.

2
Robin Krahl On

There is a difference between a null reference and an object with the value 0. To check for null references, use:

BigInteger value = getValue();
if (value != null) {
  // do something
}

To check for the value 0, use:

BigInteger value = getValue();
if (!BigInteger.ZERO.equals(value)) {
  // do something
}

To ensure the object is neither a null reference nor has the value 0, combine both:

BigInteger value = getValue();
if (value != null && !value.equals(BigInteger.ZERO)) {
  // do something
}

2015-06-26: Edited according to @Arpit's comment.