@Nullable and @NotNull
@NotNull annotations let you check nullability of a variable, parameter, or return value. They help you control contracts throughout method hierarchies, and if IntelliJ IDEA spots that the contract is being violated, it will report the detected problem, and will point to the code where
NullPointerException may occur.
For example, if you create a method where a parameter has the
@NotNull annotation, and then call this method with a parameter that potentially can be null, IntelliJ IDEA will highlight the problem on the fly.
The check is done by the Constant conditions & exceptions and @NotNull/@Nullable problems inspections. You can configure the way these inspections work in the Settings/Preferences (Ctrl+Alt+S) dialog. Go to .
When you compile your project, the IDE adds assertions to all methods and parameters annotated with the
@NotNull annotation. The assertions will fail if null is passed in code where
@NotNull is expected. You can disable this option and configure the list of annotations in the Settings/Preferences dialog Ctrl+Alt+S. Go to .
@Nullable annotation helps you detect:
- Method calls that can return null
- Variables (fields, local variables, and parameters), that can be null
Methods with the
@Nullable annotation in the parent method can have either
@NotNull annotations in the child class method.
@Nullable annotation of the parameter in the parent method requires the
@Nullable annotation in the child class method parameter.
@NotNull annotation is, actually, an explicit contract declaring that:
- A method should not return null
- Variables (fields, local variables, and parameters) cannot hold a null value
IntelliJ IDEA warns you if these contracts are violated.
@NotNull annotation of the parent method requires the
@NotNull annotation for the child class method.
Methods with the
@NotNull annotation of the parameter in the parent method can have either
@NotNull annotations (or none of them) in the child class method parameter.