Search code examples
javanullnullpointerexceptionboolean-operations

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?


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.