fenec
fenec

Reputation: 5806

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.

Upvotes: 17

Views: 85801

Answers (7)

S.P
S.P

Reputation: 8756

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

Try

c != null

in your if statement.

Upvotes: 30

The reality is that when c is null, you are trying to do null.equals so this generates an exception. The correct way to do that comparison is "null".equals(c).

Upvotes: -3

shaik
shaik

Reputation: 1

if C object having null value then following statement used to compare null value:

if (c.toString() == null) {

    System.out.println("hello execute statement");

}

Upvotes: -4

Nrj
Nrj

Reputation: 6831

Most likely Object c is null in this case.

You might want to override the default implementation of equals for Customer in case you need to behave it differently.

Also make sure passed object is not null before invoking the functions on it.

Upvotes: 3

Greg Leaver
Greg Leaver

Reputation: 801

!c.equals(null)

That line is calling the equals method on c, and if c is null then you'll get that error because you can't call any methods on null. Instead you should be using

c != null

Upvotes: 13

Midhat
Midhat

Reputation: 17810

Use c==null

The equals method (usually) expects an argument of type customer, and may be calling some methods on the object. If that object is null you will get the NullPointerException.

Also c might be null and c.equals call could be throwing the exception regardless of the object passed

Upvotes: 8

Alex Martelli
Alex Martelli

Reputation: 881477

Use c == null, since you're comparing references, not objects.

Upvotes: 11

Related Questions