Java 101: Check if a String Is Empty or Blank
How do I check my Strings? Let me count the ways...
Join the DZone community and get the full member experience.Join For Free
In Java, an empty String and a blank String are two different concepts. It’s always confusing and tricky for Java beginners to check if a String is both, empty or blank. An empty String is a String object initialized without any character, whereas a blank string is a String with a whitespace character. Always remember that a String with just whitespace may or may not be considered empty, depending on the program. Depending upon your situation, you can include the logic to check for that as well. A String with just whitespace is also referred to as a blank String in Java. In this tutorial, I will teach you a couple of right ways to check if a String is empty or blank in Java.
Check if a String Is Null or Empty in Java
To make sure we’re on the same page with our definitions, we consider a String to be empty if it’s either null or a string without any length. If a string consists of whitespace only, then we call it blank.
For Java, whitespaces are characters like spaces, tabs, and so on. Have a look at Character.isWhitespace for examples.
Below are the different ways to check if a String is empty or blank in Java.
1) Empty String Check With Java 6 and Above Using isEmpty()
This is the most readable way to check whether a String is empty or not. You can see from the code below that the first check is a null check and the second check is for emptiness.
2) Empty String Check With Java 5 and Below Using length()
This is the universal solution and works in all versions of Java, from JDK 1.0 to Java 15. This method highly recommended because of the portability advantage it provides. It is also the fastest way to check if a String is empty in Java or not.
3) Blank String Check With Java 10 and Below
You can use the solution below if your program considers a String with only whitespace as a blank String.
4) Blank String Check With Java 11 and Above
Java 11 introduced the
isBlank() method to check if the string is empty or contains whitespace characters. This makes it more straightforward to check if the string is Empty or Blank. The below example shows how to use the
You can also use Google Guava, Spring, or Apache commons to check for empty or blank Strings.
Published at DZone with permission of Dee Kay. See the original article here.
Opinions expressed by DZone contributors are their own.