459

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?

Hash
  • 4,647
  • 5
  • 21
  • 39
user2027811
  • 4,691
  • 2
  • 14
  • 10
  • 10
    This question is much better than its duplicate. More concise, better wording. – Nicolas Raoul Feb 22 '16 at 02:22
  • 11
    Not to mention it shows as the top result on Google ☺ – nikodaemus Nov 08 '16 at 15:36
  • 4
    Since Java 11 you can use isBlank() methid of String class which will check for both empty string or string consist of only white spaces. so you can do something like (str != null && !str.isBlank()), Thanks – Shivang Agarwal Jan 15 '20 at 02:41
  • `if (string == null || string.isEmpty("")) {` would be the correct null check and improved empty string check; `isBlank` would also allow whitespace (tabs, spaces). Mind: `null.equals(...)` gives a NullPointerException. – Joop Eggen Dec 07 '21 at 21:01

5 Answers5

612

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 */ }
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88
Pradeep Simha
  • 17,683
  • 18
  • 56
  • 107
  • 55
    OK to use != for null, but *never* for "" – Hovercraft Full Of Eels Feb 06 '13 at 04:14
  • 41
    Just FYI, IsEmpty() does not return true for a string containing only spaces. – bluelurker Aug 17 '16 at 12:36
  • 4
    The negation of this answer is exactly how Guava's [Strings.isNullOrEmpty](https://google.github.io/guava/releases/21.0/api/docs/com/google/common/base/Strings.html#isNullOrEmpty-java.lang.String-) is implemented. – Michael Xin Sun Jan 17 '17 at 20:23
  • 4
    @HonzaKalfus *"Calling isEmpty() returns true for string containing whitespace character"* - That is not true! " ".isEmpty() returns **false** – MestreLion Sep 01 '17 at 01:59
  • @HonzaKalfus That's not true. String.isEmpty() checks if String.length == 0 and " " has a length of 1. – Lakatos Gyula Nov 07 '17 at 14:54
  • 1
    first check for null then empty string, order is important , otherwise it will throw null pointer exception. @Pradeep add this line – user2903536 Feb 19 '18 at 12:10
  • fyi `if(!"".equals(str))`, is inelegant but works without Utils class, but I prefer `StringUtils.isEmpty()` for clarity – amdev Nov 19 '18 at 22:40
  • @bluelurker , @PradeepSimha To catch _"a string containing only spaces"_, You could add `trim()` to the if-condition. i.e `if (theItem != null && !theItem.trim().isEmpty()) {}` – steven7mwesigwa Dec 13 '18 at 23:54
  • java srouce: public boolean isEmpty() { return this.value.length == 0; } – BuffK Nov 16 '19 at 03:01
  • 8
    Since Java 11, ```str.trim().isEmpty()``` can be replaced with ```str.isBlank()``` – OOP Nov 23 '20 at 07:23
413

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
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • As a side note, the method name is a bit misleading. Intuitively `isEmpty(null)` would return false as it's not an empty string. – Steve Kuo Feb 06 '13 at 04:29
  • 7
    Note, isEmpty() just uses "return cs == null || cs.length() == 0;" Also, since commons.lang 2.0, isEmpty() no longer trims the String. So, StringUtils.isEmpty(" ") returns false - but StringUtils.isBlank(" ") returns true. – eze Jul 14 '14 at 15:52
  • 2
    @SteveKuo println(org.apache.commons.lang.StringUtils.isEmpty(null)); // true It returns TRUE only... – Abhishek Sengupta May 12 '20 at 09:48
116

You can use Apache commons-lang

StringUtils.isEmpty(String str) - Checks if a String is empty ("") or null.

or

StringUtils.isBlank(String str) - Checks if a String is whitespace, empty ("") or null.

the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 15
    For non-Java users like myself; be sure to include `import org.apache.commons.lang3.StringUtils;` and ensure your package manager has it marked as a dependency. – TJ Biddle Sep 08 '17 at 15:29
  • @TJBiddle. Great tip! I had to laugh at "for non-Java users" because I've been programming Android for years (in Java), through Eclipse and AndroidStudio, and still needed this tip. I never understood that gradle, or whatever preceeded it, was a Java "package manager". I write the Java code which should work, and then start fixing dependency problems (if any) with the assistance of StackOverflow :). This time round, after years of "ouches", I pre-empted it and put the "dependency in the package manager", before writing the code. (as below) – Stephen Hosking Aug 11 '20 at 00:12
  • To add the apache package, put `dependencies { implementation 'org.apache.commons:commons-text:1.7' }` in `build.gradle (Module app)`. If there is already a `dependencies` block then just insert a new line with this dependency. This is the latest recommended version, as of Feb '20 (see https://stackoverflow.com/a/55567755/1541141). Then clean and/or sync your project. – Stephen Hosking Aug 11 '20 at 00:40
39
import com.google.common.base.Strings;

if(!Strings.isNullOrEmpty(String str)) {
   // Do your stuff here 
}
Community
  • 1
  • 1
hari
  • 1,874
  • 1
  • 16
  • 10
37

This way you check if the string is not null and not empty, also considering the empty spaces:

boolean isEmpty = str == null || str.trim().length() == 0;
if (isEmpty) {
    // handle the validation
}
Alécio Carvalho
  • 13,481
  • 5
  • 68
  • 74