6

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?

5
  • 3
    Why 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? Commented Jan 30, 2019 at 14:45
  • merge it into the outer if. Or write a StringUtil.notNullAndEmpty(text) method Commented Jan 30, 2019 at 14:45
  • 3
    Where did you get text.equals(null) from? This expression is always false or throws an NPE. Commented Jan 30, 2019 at 14:45
  • Did you consider using Kotlin? if (text?.isEmpty() != null), and you can even add methods to String class, like String#toDisplay(). Commented Jan 30, 2019 at 14:48
  • @VinceEmigh I need to deliver null if empty Commented Jan 30, 2019 at 14:52

7 Answers 7

10

Another alternative using Guava's emptyToNull:

text = Strings.emptyToNull(text);
Sign up to request clarification or add additional context in comments.

Comments

4

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

3 Comments

Just an opinion, but using a third party library for such a minuscule task is just a waste.
@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.
@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 avoid null instead of using these utility methods.
3

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

2 Comments

You forgot to insert the return statement in your method. As a side note, starting with JDK 11, you can use text.isBlank() instead of text.trim().isEmpty().
Good catch, thanks. I've been switching between groovy and java lately and groovy doesn't require a return.
1

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.

Comments

1

You can do the same thing by using a one if statement like below,

    if (text != null && text.isEmpty()) {
        text = null;
    }

3 Comments

complete util possibly would be private String checkEmptyAndNull(String text) { if (text != null && text.isEmpty()) { text = null; } return text; }
text.equals(null) is always false, and will cause an NPE if text is null. Just write text != null (but OP made same mistake)
Just wanted to say that he can achive the same thing by using one if statement and missed the text.equals(null) part. My bad
1

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

1 Comment

Beware that this method performs whitespace trimming before actual empty string check. So trimToNull(" ") will give null.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.