Paul Boddington Paul Boddington - 6 months ago 28
Java Question

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

I am confused about the correct use of these annotations.;;

The information in the documentation for

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

For example, suppose I have a class
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
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
, android studio tells me that the parameter to
should probably be marked
too (but this is the opposite of what I want).

If I mark the parameter to the
method as
I get a warning that the condition
title == null
is always

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


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.