In this post you will know how to check if String is null or empty in java. There are 4 ways to check if String is null or empty in java. Each solution has their pros and cons and a special use case e.g. first solution can only be used from JDK7 on wards, second solution is the fastest way to check string is empty and third solution should be used if your string contains whites paces. Fourth solution is with Apache Commons Lang, one simple call does it all.
Solution1:-
Using isEmpty() method:-
This is the most readable way to check both whether the string is null or empty. you can see the below code,
if(string!=null && !string.isEmpty()){
System.out.println(“String is not null and not empty”);
}
A couple of things you need to remember about this solutions that is
the same order of check should be maintained because isEmpty() is a non-static method if you called it on null reference then Null Pointer Exception(NPE) will be thrown.
Second thing you should keep in mind is that isEmpty() method should be used from JDK7 onwards, as I mentioned earlier.
2nd solution -
Using length() function:-
This is the universal solution and works in all versions of Java, from JDK 1.0 to Java8. I highly recommend this method because of portability advantage it provides. It is also the fastest way to check if String is empty in Java or not.
if(string!=null && string.length()>0){
System.out.println(“String is not null and not empty”);
}
- One thing which is very important here is that if String contains just whitespace then this solution will not consider it as empty String. The emptiness check will fail because 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 String is empty or not. This solution first calls the trim() method on the String object to remove leading and trailing white spaces.
if(string!=null && string.trim.length()>0){
System.out.println(“String is not null and not empty”);
}
- 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 to avoid pesky issue due to whitespaces.
4th Solution -
Using isBlank() method of Apache Commons Lang
The StringUtils.isBlank(String) static method performs three checks in single method. check a String to ensure it is not null, not empty, and not white space only. In your project if you are using Apache commons Lang jar then you can definitely use this method.
import org.apache.commons.lang.StringUtils;
public boolean isNullOrEmpty(String string){
return StringUtils.isBlank(string);
}
No comments:
Post a Comment