16

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
rockit
  • 3,708
  • 7
  • 26
  • 36

4 Answers4

37

Use

stringVariable == null

To test whether stringVariable is null.

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

Pool
  • 11,999
  • 14
  • 68
  • 78
17

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
  • 957
  • 1
  • 6
  • 20
  • While the approved comment does, in fact, help to answer the "spirit" of the OP question,(they just ask for "any thoughts") I believe this answer expands a bit more on the "why" to help future readers. – Aterxerxes Apr 05 '16 at 14:02
7

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
  • 23,575
  • 2
  • 47
  • 51
  • More common is when used against a string literal, and we reverse it as: `if ("true".equals(value)) {...}`. – YoYo Nov 12 '22 at 00:12
0

The equals() method does not work with null parameter.

The method needs to have an object or string as parameter.

public boolean equals(Object anObject)

Since null is not an object. Is null an Object?.

Also refer to java 7 documentation which says that equals will give result if and only if the object passed is not null.

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)

Community
  • 1
  • 1
s_ag
  • 82
  • 1
  • 7
  • The java 7 documentation does not say that. You rephrased it giving it different meaning. What is the opposite of "give result"? "give no result"? That is not the same as true/false. So `equals()` does work with a null parameter, it just cannot be called on a `null` object. – YoYo Nov 12 '22 at 00:09