Reputation: 743
I have an array
String [] array = account.getDetails().split(',');
the account details is sometimes null, how to avoid the exception?
I did something like that, but that does not like pretty.
if (account.getDetails() == null)
{
account.setDetails("");
}
String[] array = account.getDetails().split(',');
That avoid throwing the NullPointerException
, is this okay or is there a better way?
Upvotes: 0
Views: 420
Reputation: 216
So here is the good way in my opinion, first you check if the details is not null
using ?
if it's not null
you just do the split
and assign result to variable array
, else you assign empty array of strings since details were null
:
String details = account.getDetails();
String[] array = details != null ? details.split(",") : new String[0];
Upvotes: 1
Reputation: 6300
Null check with if else
statement is ok. Also needs to be mentioned that in java8 an Optional
was introduced, that help to avoid null checking. With optional it will look like:
String[] strings = Optional.ofNullable(account.getDetails())
.map(s -> s.split(",")).orElse(new String[0]);
Upvotes: 2
Reputation: 1580
Your implementation is fine (more below), but you can avoid calling split(String)
on an empty string and do something like this:
String[] array;
if (account.getDetails() == null) {
array = new String[0];
} else {
array = account.getDetails().split(",");
}
Be careful that your implementation would return an array with one empty string if the input was null
, this will return an empty array.
As pointed out by @MarkAdelsberger you should not change the value directly on the object, this is known as god behavior.
Upvotes: 2
Reputation: 1178
If you're looking for a "prettier" way of doing it, then this is a spot that seems decent for the '?' operator (called the ternary operator)
String[] array = account.getDetails() == null? new String[]{""} : account.getDetails().split(",");
You could also change the getter or the setter/constructor so that the getDetails() method never returns a null (because it won't or because it never has a null at all).
public String getDetails() {
return details == null? "" : details;
}
Upvotes: 2