Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare an object to null!

Tags:

java

object

null

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.

like image 287
fenec Avatar asked Jun 15 '09 03:06

fenec


2 Answers

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

like image 70
SuPra Avatar answered Oct 13 '22 10:10

SuPra


!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
like image 22
Greg Leaver Avatar answered Oct 13 '22 09:10

Greg Leaver