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?
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.
We can simply compare the string with Null using == relational operator. Print true if the above condition is true.
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.
Use
stringVariable == null
To test whether stringVariable is null.
The equals method (and every other method) requires stringVariable to not be null.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With