I use object != null
a lot to avoid NullPointerException.
Is there a good alternative to this?
For example I often use:
Guava, a very useful core library by Google, has a nice and useful API to avoid nulls. I find UsingAndAvoidingNullExplained very helpful.
As explained in the wiki:
Optional
is a way of replacing a nullable T reference with a non-null value. An Optional may either contain a non-null T reference (in which case we say the reference is "present"), or it may contain nothing (in which case we say the reference is "absent"). It is never said to "contain null."
Usage:
Optional possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5