- How to check if String is not null and empty in Java? Example
- 3 Ways to check if String is null or empty in Java
- 1st solution — using isEmpty() method
- 2nd solution — Using length() function
- 3rd solution — Using trim() method
- Java check not null string
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Java: Check if String is Null, Empty or Blank
- Using the Length of the String
- Using the isEmpty() Method
- Using the equals() Method
- Using the StringUtils Class
- Free eBook: Git Essentials
- Conclusion
How to check if String is not null and empty in Java? Example
In Java, since null and empty are two different concepts, it’s a little bit tricky for beginners to check if a String is both not null and not empty. A String reference variable points to null if it has not been initialized and an empty String is a String without any character or a string of zero length. Remember, a String with just whitespace may not be considered as empty String by one program but considered as empty String by others, so, depending upon your situation, you can include the logic to check for that as well. A String with just white space is also referred to as a blank String in java. In this tutorial, I will teach you a couple of right ways to test if a String is not null and not empty in Java.
Btw, I am expecting that you are familiar with basic Java Programing and Java API in general. If you are a complete beginner then I suggest you first go through a comprehensive course like The Complete Java Masterclass on Udemy to learn more about core Java basics as well as such gems from Java API.
3 Ways to check if String is null or empty in Java
Here are my three solutions to this common problem. Each solution has its pros and cons and a special use case like the first solution can only be used from JDK 7 onward, the second is the fastest way to check if String is empty and the third solution should be used if your String contains whitespaces.
1st solution — using isEmpty() method
This is the most readable way to check for both whether String is null or not and whether String is empty or not. You can see from the below code that the first check is a null check and the second check is for emptiness.
A couple of things to remember about this solution is that you must keep the order the same because isEmpty() is a non-static method and if called on the null reference it will throw NullPointerException.
Since we are first doing a null check and then an empty check using the && operator, which is a short circuit AND operator. This operator will not check for emptiness if String is null hence no NPE. This is also a good trick to avoid NPE in Java.
Btw, you must be careful with the order you carry the null and emptiness check. For example, if you reverse the order of checks i.e. first call the isEmtpy() method and then do the null check, you will get the NullPointerException. In fact, it is one of the most common causes of NullPointerExcetpion in Java.
The second thing to keep in mind is that the isEmpty() method is available from Java SE 6 onwards, so this code will not work in Java 5 or the lower version. There you can use the length() method to check emptiness, as shown in the second example.
2nd solution — Using length() function
This is the universal solution and works in all versions of Java, from JDK 1.0 to Java 8. I highly recommend this method because of the portability advantage it provides. It is also the fastest way to check if String is empty in Java or not.
One thing which is very important here is that if String contains just white space then this solution will not consider it as an empty String. The emptiness check will fail because the string.length() will return a non-zero value. If you are considering the String with only whitespaces as empty then use the trim() method as shown in the third example.
3rd solution — Using trim() method
This is the third way to check whether the String is empty or not. This solution first calls the trim() method on the String object to remove the leading and trailing white spaces.
You can use this solution if your program doesn’t consider a String with only white-space as a non-empty. If you load data from the database or stored data into the database it’s better to trim() them before using them to avoid pesky issues due to whitespaces.
That’s all about how to check if String is not null and not empty in Java. You can use any of the above three methods but you must remember the pros and cons of each method. Sometimes you need to use the trim() method if your program’s requirement doesn’t consider a String with the only whitespace as non-empty, but other times, you might want to use the length() function to consider String with just whitespaces as empty String in Java.
As suggested by others, if you are using Google Guava, Spring, or Apache commons then just check their StringUtils class, you might get a method that does this for you like StringUtils.isBlank() from Apache Commons. Remember, even Joshua Bloch has advised in Effective Java to learn and use library functions, whenever possible, but only if you understand the fundamentals behind it.
- When to use the intern() method of String in Java? (answer)
- Why is String Immutable and final in Java? (answer)
- Why is a character array better than a String for storing the password in Java? (reason)
- How substring() method works in Java 6? (answer)
- The difference between String literal and new() String object in Java? (answer)
- How to prepare for Java interviews? (guide and resources)
Java check not null string
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Java: Check if String is Null, Empty or Blank
In Java, there is a distinct difference between null , empty, and blank Strings.
- An empty string is a String object with an assigned value, but its length is equal to zero.
- A null string has no value at all.
- A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn’t of 0 length.
String nullString = null; String emptyString = ""; String blankString = " ";
In this tutorial, we’ll look at how to check if a String is Null, Empty or Blank in Java.
Using the Length of the String
As mentioned before, a string is empty if its length is equal to zero. We will be using the length() method, which returns the total number of characters in our string.
String blankString = " "; if (blankString == null || blankString.length() == 0) System.out.println("This string is null or empty"); else System.out.println("This string is neither null nor empty");
The code above will produce the following output:
This string is null or empty
The String is blank, so it’s obviously neither null nor empty. Now, based just on the length, we can’t really differentiate between Strings that only contain whitespaces or any other character, since a whitespace is a Character .
Note: It’s important to do the null -check first, since the short-circuit OR operator || will break immediately on the first true condition. If the string, in fact, is null , all other conditions before it will throw a NullPointerException .
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.trim().isEmpty()) System.out.println("String is null, empty or blank."); else System.out.println("String is neither null, empty nor blank");
The trim() method removes all whitespaces to the left and right of a String, and returns the new sequence. If the String is blank, after removing all whitespaces, it’ll be empty, so isEmpty() will return true .
Running this piece of code will give us the following output:
String is neither null, empty nor blank
Using the equals() Method
The equals() method compares the two given strings based on their content and returns true if they’re equal or false if they are not:
String string = "Hello there"; if (string == null || string.equals("") || string.trim().equals("")) System.out.println("String is null, empty or blank"); else System.out.println("String is neither null, empty nor blank");
In much the same fashion as the before, if the trimmed string is «» , it was either empty from the get-go, or was a blank string with 0..n whitespaces:
String is neither null, empty nor blank
Using the StringUtils Class
The Apache Commons is a popular Java library that provides further functionality. StringUtils is one of the classes that Apache Commons offers. This class contains methods used to work with Strings , similar to the java.lang.String .
If you’re unfamiliar with Apache Commons’ helper classes, we strongly suggest reading our Guide to the StringUtils class.
Since we’ll be using Apache Commons for this approach, let’s add it as a dependency:
dependency> groupId>org.apache.commons groupId> artifactId>commons-lang3 artifactId> version>3.11 version> dependency>
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.11'
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
One of the key differences between StingUtils and String methods is that all methods from the StringUtils class are null-safe. It additionally provides a few methods that we can leverage for this, including StringUtils.isEmpty() and StringUtils.isBlank() :
String nullString = null; if (nullString == null) < System.out.println("String is null"); > else if (StringUtils.isEmpty(nullString)) < System.out.println("String is empty"); > else if (StringUtils.isBlank(nullString)) < System.out.println("String is blank"); >
In addition to these, their inverse methods also exist: StringUtils.isNotEmpty() and StringUtils.isNotBlank() , though, you can achieve the same functionality by using the NOT ( ! ) operator:
if (StringUtils.isNotEmpty("")) System.out.println("String is not empty"); // Equivalent to if (!StringUtils.isEmpty("")) System.out.println("String is not empty");
Conclusion
A string is an object that represents a sequence of characters. Java provides many different methods for string manipulation. In this article, we have used some of these methods such as isEmpty() , equals() , StringUtils.isEmpty() and length() to check if the String is null , empty or blank.