tags:

views:

460

answers:

5

I am trying to verify whether an object is null or not and i am 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 loop. Any help would be appreciated.

+9  A: 

Try c != null in your if statement. You're not comparing the objects themselves, you're comparing their references.

Suvesh Pratapa
+6  A: 

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

Alex Martelli
+5  A: 

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

Midhat
+8  A: 
!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
Goog
+2  A: 

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.

Nrj