Tarun Maganti
Tarun Maganti

Reputation: 3086

Is there a `boolean Object.isNull(Object object)` or something similar static utility method in Java?

Related to the following conversations -

The second link suggests a few ways to avoid != null statements.

  1. Using assert is one.
  2. Using NullObjectPattern - Not an option, since everyone dealing isn't in charge of production code.

The first link just suggests != null idea.

Object class has requiresNonNull methods which throw NullPointerException which was gonna be thrown anyway if the object was used. assert also proposes same way. If I could handle every exception then, the code would get ugly with way too many try and catches.

Using != null isn't very pretty in an object oriented sense.

I think Object.isNull and Object.isNotNull are ways to go to make code look concise and neat with also handling the situation well (I mean without verbose try...catch statements). I can easily use them in any conditional statements. This is much better than raw != null.

But, why are there no such methods? Is passing around null such a bad idea? If it is then what should we do if null is a valid response instead of != null?

Edit:

Changed the question from: Why is there no boolean Object.isNull(Object object) static utility method in Java? to Is there a boolean Object.isNull(Object object) or something similar static utility method in Java?

Upvotes: 0

Views: 867

Answers (1)

Mikhail Antonov
Mikhail Antonov

Reputation: 1367

https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html:

static boolean isNull(Object obj) Returns true if the provided reference is null otherwise returns false.

static boolean nonNull(Object obj) Returns true if the provided reference is non-null otherwise returns false.

Since 1.8, though...

Upvotes: 3

Related Questions