How to set null value if String is empty? - java

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

Related

Null Getter, when split throwing exception

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

Cleanest way to assign to a variable if an element in jsoup is defined?

I was doing this String name = doc.select("h1#name").first().text(); and I received a NullPointerException on a page where the 'h1#name' element did not exist. I'm parsing the DOM, grabbing hundreds of elements. It seems that I need to test each element before I assign, so I changed it to this:
String name = null;
if( doc.select("h1#name").first() != null && doc.select("h1#name").first().text() != null ))
name = doc.select("h1#name").first.text();
Is there a better way to do it? I'm just learning Java, and my background is in Perl, where I'd do something like this:
my $name = $doc->select("h1#name")->text if $doc->select("h1#name");
It's not a big deal, since my code does work for me. I was just wondering if there was a cleaner way to do this in Java.
You will not come arround checking all objects you go throuth to access the value you want.
To translate your perl syntax into java I would use the ternary operator:
name = doc.select("h1#name").first() != null ?
doc.select("h1#name").first().text() : null
There is no need to check doc.select("h1#name).first().text() != null too unless you have a non null value in name and you don't want to override it with null.
I would suggest a utility method, something like this:
Document mDocument;
(...)
String getElementTextOrNull (String cssQuery) {
Element e = mDocument.select(cssQuery).first();
if (e == null) {
return null;
} else {
return e.text();
}
}
Then, you can eliminate a lot of boilerplate and repetition, so your code simply becomes:
String name = getElementTextOrNull("h1#name");
You can also do other things in that method, like checking if the text is empty or if it is valid.
Of course, this may be impractical if you only get the text of a specific element once, but this is what I would suggest otherwise. Personally, I also think this is neater and more concise than the ternary operator solution proposed in the other answer.

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.

How to check if List<obj> is null?

I have a list that takes a list from my server. this list will hold whatever the server finds at the database ex.
List<OBJ> lstObj = new Arraylist<OBJ>;
Service.getOBJ(new AsyncCallback<List<OBJ>>(){
#Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
#Override
public void onSuccess(List<OBJ> result) {
//line to check if result is null
}
});
I have tried
if(result==null){
}
and also tried
if(result.isempty(){
}
but it didnt work. the list will be null if the server doesnt find any record from the database. all i need to do is check if the list is empty.
Checking if the list is empty and checking if result is null are very different things.
if (result == null)
will see if the value of result is a null reference, i.e. it doesn't refer to any list.
if (result.isEmpty())
will see if the value of result is a reference to an empty list... the list exists, it just doesn't have any elements.
And of course, in cases where you don't know if result could be null or empty, just use:
if (result == null || result.isEmpty())
Check number of elements in resulting List:
if (0==result.size()) {
// Your code
}
You will do like this:
if (test != null && !test.isEmpty()) { }
This will check for both null and empty, meaning if it is not null and not empty do your processing.
You're obviously new at this programming thing if you didn't already validate your server, so I'm trying to aim a guess at what might be going on with your server. Depending on what your "" objects are, you could have valid objects that represent data that is meaningless in different ways. For example, you may have String objects with various kinds of white space.
This happens a lot on servers that provide answers using PHP and JSP, where pages are assembled using various include mechanisms and there is white space between them.
The below should do for your code. If you want a negation logic just modify accordingly.
As also suggested by someone CollectionUtils provide just utility methods which removes such null check LOC.
result == null || result.isEmpty()
Hope this helps!

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