views:

116

answers:

1

Here is a number of code snippets that can throw NullPointerException.

01:

public void m1(@Nullable String text) {
    System.out.print(text.toLowerCase()); // <-- expect to be reported.
}

02:

private boolean _closed = false;

public void m1(@Nullable String text) {
    if(_closed)
       return;

    System.out.print(text.toLowerCase()); // <-- expect to be reported.
}

03:

public void m1(@NotNull String text) {
    System.out.print(text.toLowerCase());
}

public @Nullable String getText() {
    return "Some text";
}

public void m2() {
    m1(getText());  // <-- expect to be reported.
}

Different people have access to different static-analysis tools. It would be nice to collect information, what tools are able to detect and report the issues, and what are failing. Also, if you have your own scenarious, please, publish them.

Here my results

FindBugs (1.3.9):

  • 01: [S] Parameter must be nonnull but is marked as nullable
  • 02: [F] not reported
  • 03: [F] not reported

IntelliJ IDE 9.0.2 (Community edition):

  • 01: [S] Method invocation text.toLowerCase() may produce java.lang.NullPointerException
  • 02: [S] Method invocation text.toLowerCase() may produce java.lang.NullPointerException
  • 03: [S] Argument getText() might be null

Checker Framework (1.0.7):

  • 01: [S] dereference of possibly-null reference text
  • 02: [S] dereference of possibly-null reference text
  • 03: [S] incompatible types. found: @Nullable String, required: @NonNull String

Annotations packages:

javax.annotation.* // JSR 305
edu.umd.cs.findbugs.annotations.* // FindBugs
org.jetbrains.annotations.* // IntelliJ
checkers.nullness.quals.* // Checker Frameworks
+1  A: 

Please note that FindBugs treats @Nullable and @CheckForNull quite differently -- the former is basically saying "I have no idea whether this is supposed to allow null or not" and the latter says "This method explictly allows nulls". My team had much more useful FindBugs results when we globally changed all @Nullable to @CheckForNull in our code, since the latter is what we really had meant.

Chris Dolan
Yes, good point... Thought the provided tests results are the same when I used CheckForNull or Nullable for FindBug.
alex2k8
@alex2k8: interesting. I wonder if a more recent version of FindBugs has changed that?
Chris Dolan
The current version of FindBugs is 1.3.9 (the one I used in my tests).
alex2k8