Posts

Showing posts from August, 2024

How To Avoid NullPointerException? 3 - Optional

HowToAvoidNPE3 How To Avoid NullPointerException? 3 - Optional Optional is introduced since java 8, what is it and how do we make use of this class to avoid NPE? What is Optional? From Optional java doc A container object which may or may not contain a non- null value. Simply speaking, Optional is just like a single element Collection, the key point is it can only contain non-null value. Optional should never be null Before using Optional , one key point to know is Optional should never be null Please NEVER assign null to Optional . From API Note of Optional: A variable whose type is Optional should never itself be null ; it should always point to an Optional instance. I really hope that compiler actually enforced this, instead of putting such note. But fortunately IDE like IntelliJ will warn you for such cases. When to use Again from API Note of Optional: Optional is primarily intended for use as a method return type where there is a cl