Description
I’m encountering a false positive for rule java:S2259 (“Null pointers should not be dereferenced”) in a method where null checks are properly performed.
Code Example
public interface IdentifyPersonMapper {
default void contactInfoConverterCustom(AdditionalIdentityContactInfo source, @MappingTarget IdentifyPersonDetail target) {
if(source == null
|| source.getBirthDate() == null) {
return;
}
String birthDate = source.getBirthDate();
if(birthDate.matches("^\\d{4}-\\d{2}-\\d{2}$"))
{
LocalDate date = LocalDate.parse(birthDate);
target.setBirthDate(date);
target.setBirthYear(String.valueOf(date.getYear()));
}
else if(birthDate.matches("^\\d{4}$")){
target.setBirthYear(birthDate);
target.setBirthDate(null);
}
}
....
Issue
SonarQube raises a false positive on the line:
String birthDate = source.getBirthDate();
The rule complains that source.getBirthDate() may return null, but this is impossible because:
- The method checks if
source == nulland returns early if true - The method checks if
source.getBirthDate() == nulland returns early if true - Only after both checks pass, the code proceeds to call
source.getBirthDate()
Expected Behavior
The null check at the beginning of the method should be recognized by the analyzer, and no warning should be raised for the subsequent call to source.getBirthDate().
Environment
Please provide your environment details:
- SonarQube version: [Enterprise Edition v2025.1.1 (104738)]
- Java analyzer version: [Your version here]
- How SonarQube is deployed: [Helm]