Search code examples
javaintellij-ideaannotationsnullablenotnull

Should we always use @NotNull or @Nullable?


Should we always use @NotNull or @Nullable in method parameters even if it appears to be obvious?

@NotNull
public static int add(@NotNull int a, @NotNull int b) {
    return a + b;
}

To clarify:

Now I know that one can't pass null to primitive variable but I wanted to ask what if I would have a method (with non-primitive parameters) to which null can be passed but from the name of the method it would be obvious that you can't pass null because for example, you can't add something to null?

@NotNull
public static Integer add(@NotNull Integer a, @NotNull Integer b) {
    return a + b;
}

Solution

  • In Java primitive types such as int can never be null, this is enforced by the compiler, so the annotations in your code are completely unnecessary.

    Even if you managed to pass an Integer as a parameter (via auto-unboxing), a null value won't be allowed in most cases:

    add(1, (Integer) null);
    => Null pointer access: This expression of type Integer is null but requires auto-unboxing.
    

    But if a null does manage to be passed as an argument (say, if one of the arguments is a null attribute), the annotations won't prevent it, causing a runtime NullPointerException. If you're so concerned about passing null values (which you shouldn't), you can use Optional to gracefully handle the case when one of the arguments is null:

    public static Optional<Integer> add(Integer a, Integer b) {
        if (a == null || b == null)
            return Optional.empty();
        return Optional.of(a + b);
    }
    

    Now it'll be the caller's responsibility to determine what to do if the value couldn't be computed, with the added benefit that the caller now is aware that this could happen.