Reputation: 7394
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
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
Reputation: 53819
Try:
if(person == null || person.getId() == null) {
// do something
} else {
// do something else
}
Upvotes: 1
Reputation: 26926
Generally the test is something like:
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