Best way to verify string is empty or null
Useful method from Apache Commons:
org.apache.commons.lang.StringUtils.isBlank(String str)
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)
Just to show java 8's stance to remove null values.
String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
...
}
Makes sense if you can use Optional<String>
.
To detect if a string is null or empty, you can use the following without including any external dependencies on your project and still keeping your code simple/clean:
if(myString==null || myString.isEmpty()){
//do something
}
or if blank spaces need to be detected as well:
if(myString==null || myString.trim().isEmpty()){
//do something
}
you could easily wrap these into utility methods to be more concise since these are very common checks to make:
public final class StringUtils{
private StringUtils() { }
public static bool isNullOrEmpty(string s){
if(s==null || s.isEmpty()){
return true;
}
return false;
}
public static bool isNullOrWhiteSpace(string s){
if(s==null || s.trim().isEmpty()){
return true;
}
return false;
}
}
and then call these methods via:
if(StringUtils.isNullOrEmpty(myString)){...}
and
if(StringUtils.isNullOrWhiteSpace(myString)){...}
This one from Google Guava could check out "null and empty String" in the same time.
Strings.isNullOrEmpty("Your string.");
Add a dependency with Maven
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
with Gradle
dependencies {
compile 'com.google.guava:guava:20.0'
}