How to set null value if String is empty?
Solution 1
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;
}
Solution 2
Another alternative using Guava's emptyToNull:
text = Strings.emptyToNull(text);
Solution 3
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;
}
Solution 4
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.
Solution 5
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.
Related videos on Youtube
designuj
Updated on June 04, 2022Comments
-
designuj almost 2 years
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?
-
Dioxin over 5 yearsWhy would you want to do this opposed to using
Optional
? Why not try to eliminate null as a factor, opposed to making it a weighted value? -
XtremeBaumer over 5 yearsmerge it into the outer if. Or write a
StringUtil.notNullAndEmpty(text)
method -
Henry over 5 yearsWhere did you get
text.equals(null)
from? This expression is always false or throws an NPE. -
m0skit0 over 5 yearsDid you consider using Kotlin?
if (text?.isEmpty() != null)
, and you can even add methods to String class, likeString#toDisplay()
. -
designuj over 5 years@VinceEmigh I need to deliver
null if empty
-
-
Naman over 5 yearscomplete util possibly would be
private String checkEmptyAndNull(String text) { if (text != null && text.isEmpty()) { text = null; } return text; }
-
Florian Albrecht over 5 years
text.equals(null)
is alwaysfalse
, and will cause an NPE iftext
isnull
. Just writetext != null
(but OP made same mistake) -
Naman over 5 yearsJust an opinion, but using a third party library for such a minuscule task is just a waste.
-
Sandeepa over 5 yearsJust wanted to say that he can achive the same thing by using one if statement and missed the
text.equals(null)
part. My bad -
Tim Biegeleisen over 5 years@nullpointer Actually, maybe Java should include such methods directly in the
String
class, which would eliminate the need for third party libraries. I agree that many use cases are probably borderline. -
Holger over 5 yearsYou forgot to insert the
return
statement in your method. As a side note, starting with JDK 11, you can usetext.isBlank()
instead oftext.trim().isEmpty()
. -
Holger over 5 years@TimBiegeleisen Java did include methods, especially with the last versions. However, especially these Apache methods with their
null
handling are a step into the wrong direction. Developers should avoidnull
instead of using these utility methods. -
MikeM over 5 yearsGood catch, thanks. I've been switching between groovy and java lately and groovy doesn't require a return.