How to check if a parameter is null

13,050

Solution 1

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.

Solution 2

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.

Solution 3

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();
}
Share:
13,050
Ocasta Eshu
Author by

Ocasta Eshu

BA: English, Economics Minor: Computer Science Case Western Reserve University - 2012

Updated on November 21, 2022

Comments

  • Ocasta Eshu
    Ocasta Eshu over 1 year

    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?

    • Sarel Botha
      Sarel Botha about 12 years
      What is dead code? It's not executing? Your code is fine. Another branch is probably matching and it's not reaching this point. Debug using an IDE like NetBeans or Eclipse and step through the code to learn what is happening.