Ocasta Eshu
Ocasta Eshu

Reputation: 851

How to check if a parameter is null

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?

Upvotes: 1

Views: 17628

Answers (3)

Fahim Parkar
Fahim Parkar

Reputation: 31637

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();
}

Upvotes: 2

Woot4Moo
Woot4Moo

Reputation: 24316

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.

Upvotes: 4

Ciaran Keating
Ciaran Keating

Reputation: 2783

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.

Upvotes: 1

Related Questions