Null Getter, when split throwing exception - java

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?

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;
}

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.

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]);

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];

Related

How to set null value if String is empty?

Sometimes developers checks if Strings are null values, if yes, sets those Strings as empty value:
if (text == null) {
text = "";
}
What I want to do is to write opposite if statement:
if (text.isEmpty()) {
text = null;
}
But...first of all - I have to check (as usually) if this String is null to avoid NullPointerException, so right now it looks like this (very ugly but KISS):
if (!text == null) {
if (text.isEmpty()) {
text = null;
}
}
My class has several String fields and for all of them I have to prepare this solution.
Any basic ideas for more efficient code? Is it a good way to strech it to lambda expressions and iterate throught all String fields in this class?
Another alternative using Guava's emptyToNull:
text = Strings.emptyToNull(text);
I don't know the context in which you thought to mention streams relating to your question, but if you are open to the Apache StringUtils library, then one option would be to use the StringUtils#isEmpty() method:
if (StringUtils.isEmpty(text)) {
text = null;
}
In your example, if text is null then text.equals(null) will cause a NPE. You will want something like this:
if (text != null && text.isEmpty()) {
text = null;
}
If you want whitespace considered empty as well, you will want to call trim() before calling isEmpty():
if (text != null && text.trim().isEmpty()) {
text = null;
}
Since you want to reuse this code, it makes sense to make this a utility method that you can call from any class:
public static String setNullOnEmpty(final String text) {
return text != null && text.trim().isEmpty() ? null : text;
}
Don't use equals() to check if a string is null, but:
if (text == null)
So
if (text != null && text.isEmpty()) {
text = null;
}
This 1 line condition won't throw NPE if text is null because of short circuit evaluation.
You can do the same thing by using a one if statement like below,
if (text != null && text.isEmpty()) {
text = null;
}
I don't have a better answer to your exact problem than what has already been posted. However, I would strongly question why you would want to conflate empty strings and nulls into nulls. Nulls are generally a bad idea, a "billion-dollar mistake", to quote Tony Hoare, who himself invented null references. This blog post has some good arguments!
Have you considered going the opposite direction, converting any null strings to empty strings? That way you only have to deal with strings for most of your code and can stop worrying about null pointer exceptions.
Better yet, take a look at the Optional type, which represents an object that may or may not be present. This came about in Java 8 as a better way to represent absence than nulls. Here's a blog post that explains it.
We have a method in org.apache.commons.lang.StringUtils.trimToNull(s); and with this we can get the empty string value to null value
String text = StringUtils.trimToNull(emptyStringValue);

Check whether list object is null in java

I'm checking whether a List object is null or not using java. But I'm not sure whether it is the optimized way or not.
Here is my code:
List<String> listSCBPLNewErrMsgs= new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
The above line itself throws null pointer exception.
if(listSCBPLNewErrMsgs != null) <Right way?>
This will get all the values from the config.
Now, tomorrow if I change the config entry, this should not throw an null pointer exception
The new operator in Java can never return null. Neither can String#split.
What you may want to check, however, is that the list is not empty:
if (listSCBPLNewErrMsgs.isEmpty()) {
// do something
}
If SCBPL_NEW_ERRORMESSAGES is null that code will still fail.
Assuming that SCBPL_NEW_ERRORMESSAGES has some value or is empty, the split will return an array of size 0 or more. Changing it to a list from an array will yield either an array with 0 or more elements.
Lastly, the copy constructor will copy the content and assign it to a new list. In all scenarios, unless there is a null pointer on SCBPL_NEW_ERRORMESSAGES, the returned list (listSCBPLNewErrMsgs) will never be null, at most it will be empty, which can be checked with the isEmpty() method call.
As per your comment, if you are getting a null pointer on that line, it should be due to the fact that SCBPL_NEW_ERRORMESSAGES is null.
Try this:
List<String> listSCBPLNewErrMsgs = null;
if(SCBPL_NEW_ERRORMESSAGES != null) {
listSCBPLNewErrMsgs= new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
}
else {
listSCBPLNewErrMsgs = new ArrayList<>();
}
If you want to check whether it is null it is right way (even though it will never be null), however if you simply want to check if list is empty then you should use isEmpty() method:
if(listSCBPLNewErrMsgs.isEmpty()) {/**/}
From the looks if your code your listSCBPLNewErrMsgs object won't be null. Test if it is empty using the listSCBPLNewErrMsgs.isEmpty();
If SCBPL_NEW_ERRORMESSAGES is nulll that will throw a NPE exception indeed since you will be using the split method on null.
You can first check if that's not null:
if (SCBPL_NEW_ERRORMESSAGES != null) {
//Instantiate list
//Optional isEmpty check
}
You will first check if SCBPL_NEW_ERRORMESSAGES is not null
Then you can instantiate your list and perform an optional isEmpty check on the new list.
if(SCBPL_NEW_ERRORMESSAGES != null)
List<String> listSCBPLNewErrMsgs= new ArrayList<String>Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
No Need of listSCBPLNewErrMsgs != null as everyone said
First you have to check SCBPL_NEW_ERRORMESSAGES is null or empty
if(!TextUtils.isEmpty(SCBPL_NEW_ERRORMESSAGES))
You have to check both whether the list is null/empty or not. So I prefer
if(listSCBPLNewErrMsgs != null && !listSCBPLNewErrMsgs.isEmpty()) {
}
You need to add null check for SCBPL_NEW_ERRORMESSAGES.
if (SCBPL_NEW_ERRORMESSAGES != null && !SCBPL_NEW_ERRORMESSAGES.isEmpty()) {
In your declaration, list can not be null as your are doing new ArrayList<String>.
So no need to worry about null pointer exception.
If you wish to check for empty list.
Then you can try isEmpty() method.
if (SCBPL_NEW_ERRORMESSAGES != null && !SCBPL_NEW_ERRORMESSAGES.isEmpty()) {
List<String> listSCBPLNewErrMsgs = new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
if (!listSCBPLNewErrMsgs.isEmpty()) {
// Do something.
}
}

Using if statement to prevent "java.lang.IndexOutOfBoundsException"

I'm using a method that returns a list that is fetched from a web service. This list sometimes does not contain anything. Which results in "java.lang.IndexOutOfBoundsException"
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null)
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
I have used the if statement above to prevent the exception, but it does not work. Is there anyway I can prevent this Exception by using if statements so the program do something else in case the list is empty?
If you want to ensure the list is not null, and, contains at least two elements, do this:
if( placesList != null && placesList.size() >= 2)
The list could be defined, but have no strings in it (an empty list). You should also check the size of the list:
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null && placesList.size() > 1)
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
The list object is not null, but the contents inside can be zero
Use placeList.size() to check the number of contents inside.
If ArrayList == null returns true it doesn't mean that it's empty, it means that it hasn't been initialized and it points to null.
In order to check if your list is empty, you can use
if (!placesList.isEmpty()){
}
Just because the ArrayList object is not null, does not imply there are any elements in it.
You can call isEmpty() or size() methods to determine if there are any elements in the array.
Try this:
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null && placesList.isEmpty() == false )
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
Javadoc reference
Check to make sure the ArrayList is not null, then add a second condition ensuring the size is equal to 2 to ensure it contains what you expect
if (placesList != null && placesList.size() == 2)
Try
if (placeList.size() > 1)
you should check length of the arraylist.
something like
if (placesList.size() > 0)
One way to approach this is by:
if(placesList.isEmpty())
{
//do something here when empty
}
else
{
poi = placesList.get(0);
}

NullPointerException when comparing with null values in java [duplicate]

This question already has answers here:
Why do I get a NullPointerException when comparing a String with null?
(4 answers)
Closed 8 years ago.
if(status.equals(null))
{
status="Pass";
}
from above code it throws NullPointerException, please give solution for comparing value with null.
Looks like status itself is null. So when you do:
status.equals("null")
You're actually doing:
null.equals("null")
Which causes NPE. You should do:
if(status == null) //Now you're checking if the reference is null
//So you'll never dereference a null pointer
You might find this link useful.
Related topics:
What is null in Java?
Java null check why use == instead of .equals()
In Java "null" is a string. You want to compare the reference to null. Do the following:
if(status == null){
// code here
}
Keep in mind that String is class in Java.So whenever you call a method with unitialized object (which is a null object) then it will throw NullPointerException.In your case, there is possibility that your String status is not initialized So you need to make it sure.
BTW you should check null without using equals() method because it doesn't make sense that you are checking a null object's method for its null value.
You must do like this
if(status == null)
//Do something
only use equals method when you want to compare a String and at the stage where you are quiet sure that your String is initialized.Let say String status = ""; is a intialized String and now it is not null.Just for the info while using equals() , try to use it like "anyValue".equals(status) instead of status.equals("anyValue") because by using like "anyValue".equals(status), it will be more safe in case of null string and you wont get NullPointerException
if(status.equals("null")) //Just checking if string content/value is same
{
status="Pass";
}
By this you are just checking if value(content) of status variable is "null" String or not. IF you want to do a null check you need to do the following
if(null == status)
{
status="Pass";
}
You are not suppose to make it null as "null"! in your case compiler consider it as string.
if(stringVariable!=null)
{
//ur Code
}
(OR)
if(stringVariable.equals(null))
{
//Ur code
}
In case if ur working with string array you can do it as following
if(stringArray.isEmpty())//checks length of String array
{
//ur code
}
You cannot use .equals with a null . Use :
if(status == null) {
//Do something
}
This is exactly the reason why the HashMap cannot store more than one null values . Because it always compares the key with other valuues and if a null is inputted the second time , it throws NPE .
You are getting this error since status is null.

Comparing string array in JAVA

I have the following code within a for loop to see if a string equals a search string:
if(Data.coord[i].equals(Data.search))
I've tested the code with exact values i.e if 1=1 and the rest of the code works fine. It just doesn't like the string comparison. The consol gives out this error:
Exception in thread "main" java.lang.NullPointerException
at highercoursework.Search.main(Search.java:16)
at highercoursework.Main.main(Main.java:16)
Thanks
You should compare the constant to your parameter since it can be null.
For example if Data.search is a constant which you are searching for you should do this:
if(Data.search.equals(Data.coord[i]))
In this case you won't end up trying to call methods on a null reference and you won't need unnecessary null checks either.
You have an unpopulated element in your array i.e.
Data.coord[i]
is null. Note that Data.search could be null, but the equals() method will handle this. You just need to perform the lement check first.
String[] coord = new String[100];
This will mean you can assign something to coord[0] but until you do that coord[0] is null. Hence the null pointer exception.
You can try.
String data= Data.coord[i];
if(data != null && data.equals(Data.search))
you can avoid your problem in two ways:
In the case coord[i] should not be null
if (Data.coord[i] != null) {
if(Data.coord[i].equals(Data.search)) {
}
} else {
logger.error("Unexpected Behavior: coord[i] should not be null");
}
Note: You can replace the logger message by a more appropriated code that fit to your requirement.
In the case your your coord[i] can be null
comparing in this way won't throw an exception if Data.coord[i] is null. (Assuming Data.search is a constant and can't bu null) So the rules for this case is: use in priority a String object constant to call the method equals.
if (Data.search.equals(Data.coord[i])) {}
Read this to understand What is a Null Pointer Exception?
if coord[] is initialized properly, value of Data.coord[i] may be null. You can check
if(Data.coord[i] != null && Data.coord[i].equals(Data.search)) {}
Try this:
if(DATA != null && Data.coord[i].equals(Data.search))

Categories

Resources