How to check if my string is equal to null?

Roman picture Roman · Apr 8, 2010 · Viewed 506.1k times · Source

I want to perform some action ONLY IF my string has a meaningful value. So, I tried this.

if (!myString.equals("")) {
doSomething
}

and this

if (!myString.equals(null)) {
doSomething
}

and this

if ( (!myString.equals("")) && (!myString.equals(null))) {
doSomething
}

and this

if ( (!myString.equals("")) && (myString!=null)) {
doSomething
}

and this

if ( myString.length()>0) {
doSomething
}

And in all cases my program doSomething in spite on the fact that my string IS EMPTY. It equals to null. So, what is wrong with that?

ADDED:

I found the reason of the problem. The variable was declared as a string and, as a consequence, null assigned to this variable was transformed to "null"! So, if (!myString.equals("null")) works.

Answer

polygenelubricants picture polygenelubricants · Apr 8, 2010
if (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) should return 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.