U3 Data for Social Good Project - Null Pointer Exception

I was helping my student with their project and I was receiving a null pointer exception that I was able to fix but don’t know why the fix woks. Here is a link to the full project but I will highlight the code snippets that are causing an issue.

The student makes an array of Strings that contains album names and null values. They wanted to print the values that were not null and the following works:

But when the student had initially written the condition using the .equals() method, it produced a null pointer exception:

Also, I was wondering if null was stored as a String so I also tried “null” in the condition statement and that did not work also:

If someone could break this down for me I’d really appreciate it.

Hi Sam!
On line 25 the symbol not found error in the initial code is from a.equals(“null”) is missing the letter “s” at the end of equals- your student had just equal with no “s”.

As to why the != approach works, I’m wondering if it is because it is looking at what is stored in stack memory for the String, and the address there isn’t null, so the condition if (a != null) is true and the block of code runs. I’m not sure of this, and would love to hear others’ thoughts.


1 Like

Good catch @lindsay.davis! The method should be .equals() instead of .equal().

I changed it to .equals() and I still get that null pointer exception.

Here is another response that I got from the AP CS A Facebook group:

When you test for null for objects, you are testing for references (or rather if a has a reference), so you use == or !=.
You don’t use .equals with Strings and testing for null because .equals compares the contents of the String, not the references. You can’t use any String method if a is null - there is no object to call the method on, which is why you get the Null Pointer Exception. The computer is saying, “HEY!!! a has no object! I can’t call that method on nothing!!!”

1 Like

Thanks for the update!