Question

I'm trying to test for null parameters but you cannot compare an object to null.

The following is dead code:

    } else if(x == null){
        throw new NullPointerException("Parameter is null");
    }

How do I rewrite it to gain the desired effect?

Was it helpful?

Solution

You don't say explicitly, but this looks like Java because of the NullPointerException. Yes, you can compare an object reference to null, and so this code is fine. You might be mixing it up with SQL, where nothing compares equal to null.

OTHER TIPS

In Java you can compare to the value null. The standard way to do this is as follows:

String s = null;
if(s == null)
{  
    //handle null
}  

Typically throwing an NPE is a poor practice in the real world.

To use handle in the Java literal sense of the word

Foo foo = bar.couldReturnNull();
try {
   foo.doSomething();
} catch (NullPointerException e) {
   System.out.println("bar.couldReturnNull() returned null");
   throw new NullPointerException();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top