iamukt iamukt - 1 month ago 30
Java Question

SonarQube Blocker Issue NullPointerException might be thrown as 'contacts' is nullable here

I have a method that returns list of contacts. When I am running this code on SonarQube server. It shows a blocker issue stating NullPointerException might be thrown as 'contacts' is nullable here.. How to resolve this?

List<Contact> getContactDetails(){...}

public void checkSize() {
List<Contact> contacts = getContactDetails();
syso(contacts.size());
}

Answer

Depending on your implementation of getContactDetails(), this method might return null, and so the line

      syso(contacts.size()); 

might fail due to an NPE because contacts could be null.

Fix this by either adding

if(contacts != null) {
    syso(contacts.size()); 
} else {
    // exception, error handling or nothing
}

or by not returning null in getContactDetails().