False positive for NullPointerException

  • Operating system: Windows 11 pro 22H2
  • SonarLint plugin version:
  • Programming language you’re coding in: Java
  • Is connected mode used:
    • Connected to SonarCloud or SonarQube (and which version): SonarQube Developer Edition Version 9.6 (build 59041)

I’m getting a null pointer alert inside a condition that checks for that same null pointer.
I’m using org.springframework:spring-web RestTemplate to perform an API call, and if I manage to get a response I’m checking that the body is not null. I then try to use that body for logging purposes, but sonar reports the body as nullable, although I’m explicitly checking that it is not.

Any assistance will be much appreciated. Thanks!


In many cases, there is no guarantee in Java that two consecutive calls to a method (in your case response.getBody()) will return the same value every time. For example, in a multithreaded environment, a concurrent thread could change the response internal state between two calls.
Maybe in your case, it can’t happen because response is immutable, but our analyzer is not able to determine it.

To fix the possible race condition, we usually recommend calling the method only once, using a local variable:

var body = response.getBody();
if (body != null) {
  logger.info(xxx, body.getStringRepresentationForLog());
  return body;
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.