In Java, we use a reference type to gain access to an object, and if no object is present, we set such reference to null to imply the absence of a value. The use of null is so common that we start to over-simplified or overuse it. Null checks in programs are often overlooked by programmers causing serious bugs in program's code. NullPointerExceptions are a RuntimeExceptions that can be thrown during the normal operation of the Java Virtual Machine (JVM).
Java 8 introduces a new class called java.util.Optional<T> that encapsulates an optional value. 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 (value is present), or it may contain nothing (value is absent).
This series will give us a comprehensive guides on what is Optional, Optional's API, and the best practice on how to use it correctly.
Tutorials in this series:
Java 8 Optional Overview With ExamplesNull checks in programs are often overlooked by programmers causing serious bugs in program's code leading to NullPointerExceptions. The Optional class was introduced in Java 8 to handle optional values instead of a null reference.
Java Optional Class Featuresjava.util.Optional which introduced in Java 8 is keep improving through Java release. There are new methods introduced like ifPresentOrElse(), or(), stream(), orElseThrow(), and isEmpty(). As Java programmer, we need to understand and master this API.
OptionalDouble, OptionalInt, and OptionalLongJava created class OptionalDouble, OptionalInt, and OptionalLong as wrappers for primitive types double, int, and long. The use of these classes are preferred for accessing their respective primitive types instead of using generic Optional class.
Using Java Optional CorrectlyJava 8 added a new class to handle nullability, java.util.Optional. But many people use it wrongly, or overuse it. This article will give a simple guide how to use Optional correctly.