intellij-idea Inspections @NotNull / @Nullable inspections


Example

These inspections are extremely useful for preventing NullPointerExceptions. By default they are disabled. You can find these inspections in Inspections preferences: Java | Probable bugs | Constant conditions & exceptions and @NotNull/@Nullable problems. There you can also configure your annotations. You can use this manual to add JetBrains annotations into your project.

For example, consider this methods:

enter image description here

If getString can't possibly return null, everything is fine. But if we enable our inspections and in some cases it can return null, we will immediately will see inspection triggered:

enter image description here

which says 'null' is returned by the method which is not declared as @Nullable. And if we hit Alt + Enter, there will be an option Annotate method as '@Nullable'. If we hit Enter again, our code will look like that:

enter image description here

with inspection triggered on length() method saying Method invocation 'length' may produce 'java.lang.NullPointerException'. And if we go further and introduce the result of getString() method as a variable, after hitting Alt + Enter IDEA will suggest a few ways to fix this inspection:

enter image description here

This way you can inspect your code on-the-fly, and fix all potential NullPointerExceptions. If you want to check your whole project (or some random scope), you can use Analyze | Inspect code. Just make sure that your selected inspections profile has all necessary inspections enabled.