Java Optional Guide

Kamer Elciyar
4 min readMay 3, 2020

If you are not a paid Medium member you can read it here.

1. What is the purpose of Optional Class?

If you have been into coding for a while, you should have encountered Null Pointer Exception before. If you try to use a reference type that doesn’t point anything in the memory, you get NullPointerException. This sentence may be complicated, see the example below:

String name = null;System.out.printf(name);

I declared a name variable that points to null and tried to print it. This will throw NullPointerException since name variable doesn't show anywhere in the memory. Generally, you do not assign null to a variable and print it. But there are many cases you may accidentally see this runtime exception. If you want to see all cases read docs.

Programmers are used to deal with this exceptions by null checking. (if(name != null)). But this makes the code ugly and a programmer cannot be sure if there is a possibility of null return from a method he/she called. Many of the programming languages have different methods to deal with Null Pointer Exception. Java Optional is one of them since Java 8. Optionals are objects that may have null or non-value inside. You can check an optional object whether the value is null or not and get the value if it is not. Returning…

--

--