melvynkim
melvynkim

Reputation: 1655

Java: @NonNull for int?

I'm looking for @NonNull equivalent Java annotation for primitive data type. I know primitive data cannot be null, but I wasn't able to find an alternative.

What I'd like to achieve is logically equivalent to:

int mPageNumber;

public void updatePage(@NonNull final Integer nonNull) {
    mPageNumber = nonNull.intValue();
}

I tried:

int mPageNumber;

public void updatePage(@NonNull final int nonNull) {
    mPageNumber = nonNull;
}

And I get the following lint warning:

Primitive type members cannot be annotated. This inspection reports problems related to @Nullable and @NotNull annotations usage configured in Constant conditions & exceptions inspection.

What can I put in place of @NonNull and Integer in updatePage method above, so that I can have int as an argument, not Integer?

Upvotes: 9

Views: 14669

Answers (2)

Ben
Ben

Reputation: 934

As others pointed out, int itself doesn't need an annotation.

However, you might want to control where collections (including arrays) permit nulls. Primitive arrays can take an annotation on the square brackets, since the array itself is a reference type and can be null.

Here are some examples. Note that Lists are more readable. You can also annotate the contents of Maps if you, e.g. don't want null keys.

int noPossibleNullValue = 42;
// int noPossibleNullValue = null; // error
@NotNull Integer prohibitByAnnotation = 42;
prohibitByAnnotation = null; // warning
int @NotNull [] arrayOfInts = {1, 2, 3};
// arrayOfInts = {1, 2, null}; // error
arrayOfInts = null; // warning
int @NotNull [] @Nullable [] arrayOfArraysOfInts = {null, {3, 4, 5}};
arrayOfArraysOfInts = null; // warning
@Nullable List<@NotNull Integer> listOfIntegers = List.of(3, 4, 5);
listOfIntegers = List.of(3, 4, null); // warning

Recall that all collections, including arrays, are reference values, so they can be null even if their elements can't.

Here's a demonstration of the syntax on Godbolt, so you can verify for yourself that it compiles on all the versions of Java they support. If you want to use those annotations for real, you'd want something like BeanValidation, or your IDE's built-in annotations and checking facilities.

Upvotes: 1

Luan Vo
Luan Vo

Reputation: 231

You should change the mPageNumber type to Integer.

As int type can not be null, but Integer can do.

Upvotes: 2

Related Questions