Java NullPointerException: How Can I Fix a Null Pointer Exception in My Code?

  • Context: Comp Sci 
  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    Java
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 3K views
magnifik
Messages
350
Reaction score
0
For the following segment of code, I am getting a null pointer exception when trying to access any value in a list (doubly-linked with dummy nodes) AFTER a null value. For example, if I have the following list of integers:

0, 1, 2, 3, null, 4, 5

and I run the function list.contains(0) or list.contains(1)...list.contains(null), the program works as it should. When I try to call list.contains(4) or list.contains(5), I receive a null pointer exception. I know the order in which I use == and .equals() matters, but should I separate it into multiple if statements? I tried to do so, and I was not receiving any different results.

for (Node cursor = _head._next; cursor != _tail; cursor = cursor._next){
if ((o == null & cursor._data == null) || cursor._data.equals(o)) // o is the Object data
return true;
 
Physics news on Phys.org
Hi magnifik! :smile:

You cannot use the function cursor._data.equal() if cursor._data is a null pointer.
Your current code does not prevent this (which manifests when you have o=4).

I recommend turning it into an if-statement where you just check if cursor._data is a null pointer, and then take appropriate action.
 
You can also consider using a try-catch statement similar to this:
Code:
try {
    cursor._data.equals(o)
} 
catch (NullPointerException e) {
    System.out.println("NullPointerException thrown");
}

I'm presuming that "I like Serena" is correct in that the exception is being caused by cursor._data.equal().
 
I like Serena said:
Hi magnifik! :smile:

You cannot use the function cursor._data.equal() if cursor._data is a null pointer.
Your current code does not prevent this (which manifests when you have o=4).

I recommend turning it into an if-statement where you just check if cursor._data is a null pointer, and then take appropriate action.

thank you for the suggestion! my program functioned correctly after using a series of if statements rather than my single one :)
 
magnifik said:
thank you for the suggestion! my program functioned correctly after using a series of if statements rather than my single one :)

Good! :smile:

And here's one for the road:

Code:
bool found = false;
for (Node cursor = _head._next; (cursor != _tail) && !found; cursor = cursor._next)
{
   // o is the Object data
   if (cursor._data == null) 
   {
      found = (o == null);  
   }
   else 
   {
      found = cursor._data.equals(o);
   }
}
return found;