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 */ }
Answer from Pradeep Simha on Stack OverflowCorrect 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 */ }
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
Videos
string == null compares if the object is null. string.equals("foo") compares the value inside of that object. string == "foo" doesn't always work, because you're trying to see if the objects are the same, not the values they represent.
Longer answer:
If you try this, it won't work, as you've found:
String foo = null;
if (foo.equals(null)) {
// That fails every time.
}
The reason is that foo is null, so it doesn't know what .equals is; there's no object there for .equals to be called from.
What you probably wanted was:
String foo = null;
if (foo == null) {
// That will work.
}
The typical way to guard yourself against a null when dealing with Strings is:
String foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
// Do something here.
}
That way, if foo was null, it doesn't evaluate the second half of the conditional, and things are all right.
The easy way, if you're using a String literal (instead of a variable), is:
String foo = null;
...
if ("some String".equals(foo)) {
// Do something here.
}
If you want to work around that, Apache Commons has a class - StringUtils - that provides null-safe String operations.
if (StringUtils.equals(foo, bar)) {
// Do something here.
}
Another response was joking, and said you should do this:
boolean isNull = false;
try {
stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
isNull = true;
}
Please don't do that. You should only throw exceptions for errors that are exceptional; if you're expecting a null, you should check for it ahead of time, and not let it throw the exception.
In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.
s == null
won't work?
Copyif (myString != null && !myString.isEmpty()) {
// doSomething
}
As further comment, you should be aware of this term in the equals contract:
From Object.equals(Object):
For any non-null reference value
x,x.equals(null)shouldreturn false.
The way to compare with null is to use x == null and x != null.
Moreover, x.field and x.method() throws NullPointerException if x == null.
If myString is null, then calling myString.equals(null) or myString.equals("") will fail with a NullPointerException. You cannot call any instance methods on a null variable.
Check for null first like this:
Copyif (myString != null && !myString.equals("")) {
//do something
}
This makes use of short-circuit evaluation to not attempt the .equals if myString fails the null check.
Check whether value is null first. Otherwise value.equals() will throw a NullPointerException.
if (value == null || value.equals("")) {
value = "Anonymous";
}
First you need to reorder your if condition, otherwise you could run into NPEs. Additionally, the string length can never be lower than 0, so that check is not needed:
value==null||value.equals("")
Alternatively, if you can use Apache Commons Lang you could use StringUtils.isEmpty(value) which handles all the relevant cases for you.
Just use a simple ==. There's no need to overcomplicate this.
Another Option if you are using Java 8 you can use Optional::ofNullable
Optional.ofNullable(myString).isPresent()// true if not null, false if null
You can even use :
Optional.ofNullable(myString)
.orElseThrow(() -> new Exception("If null throw an exception"));
There are many Options, just read the documentation
But as Mureinik mention in his answer == is enough in your case.
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)
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)){...}