NullPointerException could be thrown false positive

  • Java
  • java:S2259
  • SonarQube v9.9
  • Why do you believe it’s a false-positive/false-negative?
  • SonarQube is reporting A “NullPointerExcpetion” could be thrown when add() is called in the following but stuff cannot be null when add is called
    public Collection<String> notNullFalsePositive(Object x) {
        final boolean y = x == null;
        final Collection<String> stuff = y ? new ArrayList<>() : null;
        if (y) {
            stuff.add("something");
        }
        return stuff;
    }

Interestingly, it does not report a potential NullPointerException for the following simpler snippet.

   public Collection<String> notNullFalsePositive(boolean y) {
        final Collection<String> stuff = y ? new ArrayList<>() : null;
        if (y) {
            stuff.add("something");
        }
        return stuff;
    }

Hello @stephenrpalmer ,

First, thank you for your patience and the very precise reproducer!

I have been able to reproduce it locally. It’s indeed an FP.

I could not identify the root cause precisely, but in this situation, the symbolic execution engine on which this rule relies is facing a contradiction and obviously takes the wrong decision… While stuff is known to be NOT_NULL in the engine, it still deduces it is null and reports.

I created the following ticket to track this (non-trivial) issue: SONARAJVA-4533.

Cheers,
Michael

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