Amal Prasad
Amal Prasad

Reputation: 157

Null Pointer Exception in If condition

     Product p = dao.checkProduct(pnumber);
     ExpensiveProduct ep = dao.checkexpensiveProduct(pnumber);
     if ((p.getNumber() == null)&&(ep.getNumber()==null) ){ // java.lang.NullPointerException 
     //do something

     }else{
    //do something

      }

Why this statement giving java.lang.NullPointerException Do I have any other way to check this?

Upvotes: 1

Views: 3280

Answers (5)

saum22
saum22

Reputation: 882

check your p variable and ep variable .One of them is null.check why

 dao.checkProduct(pnumber)  

or

dao.checkexpensiveProduct(pnumber); is returning null

Upvotes: 1

Pops
Pops

Reputation: 30828

NullPointerExceptions (NPEs) occur when you call a method or access a property of a null object.

To check for nulls, you could print the values of your variables before you try to use them, or step through your program with a debugger and check what the variables' values are when you reach the line where the exception happens.

EDIT:
Regarding your comment

i need to check p.getNumber() and ep.getNumber() both returning null and get ture on that statement

your existing code

if ((p.getNumber() == null)&&(ep.getNumber()==null) )

is already doing that. Since you're getting an NPE on that line, p itself is null, or ep is null, or both. You should examine your checkProduct() and checkexpensiveProduct() methods, where p and ep are set, to see if they're working correctly.

Upvotes: 1

Renato Lochetti
Renato Lochetti

Reputation: 4568

What line is giving the NullPointerException? Be sure that p or ep are not null.

Upvotes: 0

duffymo
duffymo

Reputation: 308763

Try it like this:

if ((p != null) && (p.getNumber() == null) && (ep != null) && (ep.getNumber()==null) ){

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

The only non-trivial possibility where this code can throw NPE is pnumber being Integer where checkProduct() or checkexpensiveProduct() expects int (or similar).

Other trivial reasons are dao or p being null (easy to check).

Upvotes: 3

Related Questions