IntelliJ IDEA 2022.1 Help

@Nullable and @NotNull

@Nullable and @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.

Nullability

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 Editor | Inspections | Java | Probable bugs.

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 Build, Execution, Deployment | Compiler.

Runtime assertions

@Nullable

The @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 @Nullable or @NotNull annotations in the child class method.

The @Nullable annotation of the parameter in the parent method requires the @Nullable annotation in the child class method parameter.

@NotNull

The @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.

The @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 @Nullable or @NotNull annotations (or none of them) in the child class method parameter.

If @NotNull has the _TYPE_USE_ target, it’s applied to the array element type, not to the array type itself. To annotate the array type with the TYPE_USE annotation, use the byte @NotNull [] bytes syntax.

Last modified: 10 August 2022