Paul Boddington Paul Boddington - 1 month ago 7
Java Question

What are the correct uses of @NonNull and @Nullable?

I am confused about the correct use of these annotations.

android.support.annotation.NonNull;
android.support.annotation.Nullable;


The information in the documentation for
@NonNull
says:


Denotes that a parameter, field or method return value can never be null.


What does this mean in the case of parameters, when there's nothing to stop you passing
null
?

For example, suppose I have a class
MyObject
and that an instance may or may not have a title.

public final class MyObject {

private String title = null;

public void setTitle(String title) {
if (title == null)
throw new NullPointerException();
this.title = title;
}

public void clearTitle() {
title = null;
}
}


Here I am using
null
to represent the absence of a title, but this is an implementation detail, so I wouldn't want a single method for setting and clearing the title.

If I mark the field
title
as
@Nullable
, android studio tells me that the parameter to
setTitle
should probably be marked
@Nullable
too (but this is the opposite of what I want).

If I mark the parameter to the
setTitle
method as
@NonNull
I get a warning that the condition
title == null
is always
false
.

What is the correct use of these annotations in a case like this? If
@NonNull
means that a parameter can never be
null
is it wrong to use it to mean should not be
null
? If yes, is there a correct way to indicate this?

Answer

The point is that this annotation is some kind of contract, so you don't need to make checks if you annoate your methods correctly. Android Studio will check that you don't mess with it. You can still ignore it, but this will result compiler warnings.

If you omit that useless (by contract) security checks it will properly throw nullpointerexceptions. But the developer was warned with your annotation.

Comments