Search code examples
javaobjectnullcompare

Compare an object to null in Java


I am trying to verify whether an object is null or not, using this syntax:

void renderSearch(Customer c) {
    System.out.println("search customer rendering>...");
    try {
        if (!c.equals(null)) {
            System.out.println("search customer  found...");
        } else {
            System.out.println("search customer not found...");
        }
    } catch (Exception e) {
        System.err.println("search customer rendering error: "
                + e.getMessage() + "-" + e.getClass());
    }
}

I get the following exception:

search customer rendering error: null
class java.lang.NullPointerException

I thought that I was considering this possibility with my if and else statement.


Solution

  • You're not comparing the objects themselves, you're comparing their references.

    Try

    c != null
    

    in your if statement.