Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a NullPointerException when comparing a String with null?

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?

like image 744
rockit Avatar asked Mar 01 '10 18:03

rockit


People also ask

How do you fix a NullPointerException?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Can you compare a string to null?

We can simply compare the string with Null using == relational operator. Print true if the above condition is true.

What could be the reason if you are getting NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.


2 Answers

Use

stringVariable == null

To test whether stringVariable is null.

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

like image 200
Pool Avatar answered Oct 16 '22 10:10

Pool


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.

like image 29
Jama22 Avatar answered Oct 16 '22 11:10

Jama22