17

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.

1
  • 1
    plus. if and else is not called a loop. its a condition Commented Jun 15, 2009 at 4:00

7 Answers 7

30

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

Try

c != null

in your if statement.

Sign up to request clarification or add additional context in comments.

Comments

13
!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

Comments

11

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

Comments

8

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

Comments

3

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.

Comments

-3

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).

Comments

-4

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

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

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

}

1 Comment

Nope. c itself is null, so you'd get a NullPointerException.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.