views:

178

answers:

4

My code is breaking on the following line with a nullpointerexception:

 if (stringVariable.equals(null)){

Previous to this statement, I declare the stringVariable and set it to a database field.

In this statement, I am trying to detect if the field had a null value, but unfortunately it breaks!

Any thoughts?

+15  A: 

Use

stringVariable == null

To test whether stringVariable is null.

The equals method (and every other method) requires stringVariable to not be null.

Pool
A: 

It is never wise to call a method, be it equals() or otherwise,on a variable which may be null. That is why one usually does something like:

if ( var != null && var.method(something) ) {
  // var.method() was true
} else {
  // var is null or var.method is false
}

In your special case it would be sufficient to do

if (stringVariable == null) {
}

when working with Strings it can pay to check out Apache Commons StringUtils.

It always pays to check out the apache commons libraries as they have lots of optimized utilities (for Strings, Collections, Dates and such) which tend to be better than home-written ones.

extraneon
+1  A: 

if stringvariableis already null, it doesn't exist as a String object anymore, so it won't even have a .equals method! So in the event when stringvariable is null, what you are really doing is null.equals(null), at which point you'll get the NullPointerException because null doesn't have a .equals() method.

Jama22
A: 

It may be worth mentioning the static method:

String.IsNullOrEmpty(stringVariable)

This also returns true for a zero-length string, but it's a very useful method and there for good reason!

Dan Puzey
It's very useful... if you're doing .Net development. Not so much for Java. :P
Michael Myers