Java 8 Optional Explained with code samples
Java 8 has introduced a bunch of new features. The Optional feature introduced by Java 8 helps in avoiding unexpected exceptions. In this article, I will be covering this feature in detail. Edit Optional Introduction An optional can be used to represent a value that can either be present or absent. Many times methods return a null value. If the code that invokes the method expects a non-null value, this can result in a NullPointerException . To avoid this, you need to add explicit null checks in your code. This can make the code difficult to read. Consider the following code: Person person = new Person();if(person != null){ // Null Check String name = person.getName();} The above code needs to have an explicit null check for Person object. Only if the person object is not null, the code invokes the getName method. Java 8 Optionals help to avoid explicit null checks like this. So you can re-write the above code using an Optional as follows: Optional<Person> person = Option...