Android TextUtils isEmpty vs String.isEmpty

JavaAndroid

Java Problem Overview


What is difference between TextUtils.isEmpty(string) and string.isEmpty?

Both do the same operation.

Is it advantageous to use TextUtils.isEmpty(string)?

Java Solutions


Solution 1 - Java

Yes, TextUtils.isEmpty(string) is preferred.


For string.isEmpty(), a null string value will throw a NullPointerException

TextUtils will always return a boolean value.

In code, the former simply calls the equivalent of the other, plus a null check.

return string == null || string.length() == 0;

Solution 2 - Java

In class TextUtils

public static boolean isEmpty(@Nullable CharSequence str) {
    if (str == null || str.length() == 0) {
        return true;
    } else {
        return false;
    }
}

checks if string length is zero and if string is null to avoid throwing NullPointerException

in class String

public boolean isEmpty() {
    return count == 0;
}

checks if string length is zero only, this may result in NullPointerException if you try to use that string and it is null.

Solution 3 - Java

Take a look at the doc

for the String#isEmpty they specify:

> boolean > isEmpty() > Returns true if, and only if, length() is 0.

and for the TextUtils.isEmpty the documentation explains:

> public static boolean isEmpty (CharSequence str) > > Returns true if the string is null or 0-length.

so the main difference is that using the TextUtils.isEmpty, you dont care or dont need to check if the string is null referenced or not,

in the other case yes.

Solution 4 - Java

TextUtils.isEmpty() is better in Android SDK because of inner null check, so you don't need to check string for null before checking its emptiness yourself.

But with Kotlin, you can use String?.isEmpty() and String?.isNotEmpty() instead of TextUtils.isEmpty() and !TextUtils.isEmpty(), it will be more reader friendly

So I think it is preferred to use String?.isEmpty() in Kotlin and TextUtils.isEmpty() in Android Java SDK

Solution 5 - Java

String?.isNullOrEmpty

might be what you are looking for

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuriView Question on Stackoverflow
Solution 1 - JavaOneCricketeerView Answer on Stackoverflow
Solution 2 - JavaAhmed MostafaView Answer on Stackoverflow
Solution 3 - JavaΦXocę 웃 Пepeúpa ツView Answer on Stackoverflow
Solution 4 - JavaWackaloonView Answer on Stackoverflow
Solution 5 - JavaYagnaView Answer on Stackoverflow