java123999
java123999

Reputation: 7394

How to correct use an if/else statement looking for a null value?

My current code is as follows (note that getId() returns a string value):

 if(person.getId()==null){

    //do something
else{

    //do something else

}

However, I am still getting a null Pointer exception if the value for person.getId() is null.

How can I fix this?

Upvotes: 0

Views: 948

Answers (3)

agilob
agilob

Reputation: 6223

Take a read about Optional that was introduces in Java8

for some classes, like String, you can do "value".equals(myString) instead myString.equals("value"), if myString is null assertion will fail instead throw NPE.

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53819

Try:

if(person == null || person.getId() == null) {
    // do something
} else {
    // do something else
}

Upvotes: 1

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

Generally the test is something like:

  • Object is not null
  • property of object is what is needed

For your example you need probably to do something if person exists and has no id.

if (person != null && person.getId() == null) {
    // Do something, for example create person on the db
} 

This solve the problem that person is null.


Note that probably having person null here is an error.

Upvotes: 2

Related Questions