I'm parsing HTML data. The String
may be null
or empty, when the word to parse does not match.
So, I wrote it like this:
if(string.equals(null) || string.equals("")){ Log.d("iftrue", "seem to be true"); }else{ Log.d("iffalse", "seem to be false"); }
When I delete String.equals("")
, it does not work correctly.
I thought String.equals("")
wasn't correct.
How can I best check for an empty String
?
Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string. isEmpty() || string.
You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.
However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name. Remarks. IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False.
isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. The isEmpty() method of String class is included in java string since JDK 1.6. In other words, you can say that this method returns true if the length of the string is 0.
Correct way to check for null or empty or string containing only spaces is like this:
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
You can leverage Apache Commons StringUtils.isEmpty(str)
, which checks for empty strings and handles null
gracefully.
Example:
System.out.println(StringUtils.isEmpty("")); // true System.out.println(StringUtils.isEmpty(null)); // true
Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str)
.
Example:
System.out.println(Strings.isNullOrEmpty("")); // true System.out.println(Strings.isNullOrEmpty(null)); // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With