javax.annotation: @Nullable vs @CheckForNull

vitaly picture vitaly · Sep 6, 2012 · Viewed 67.7k times · Source

What is the difference between the two? Both seem to mean that the value may be null and should be dealt with accordingly i.e. checked for null.

Update: The two annotations above are part of JSR-305/FindBugs: http://findbugs.sourceforge.net/manual/annotations.html

Answer

lbalazscs picture lbalazscs · Sep 6, 2012

I think it is pretty clear from the link you added: if you use @CheckForNull and the code that uses the value does not check for null, FindBugs will show it as an error.

FindBugs will ignore @Nullable.

In practice this annotation is useful only for overriding an overarching NonNull annotation.

Use @CheckForNull in the cases when the value must always be checked. Use @Nullable where null might be OK.

EDIT: it seems that @CheckForNull is not well supported at the moment, so I suggest avoiding it and using @NonNull (also see Which @NotNull Java annotation should I use?). Another idea would be to get in touch directly with the FindBugs developers, and ask their opinion about the inconsistency in the documentation.