I came across Optionals recently in Java 8( A bit late yes). and I dont understand what is so special about them. The official documentation does say that it makes your code more readable and protects it against null pointer exceptions. Consider the following example.
Suppose, we have a method called getString() which ofcourse returns a string and we store in a variable called sample.
String sample=getString()
Now, if we do the following-
Optional<String> stringOptional=Optional.of(sample)
and sample is null, the above statement will throw a null pointer exception. Suppose, we use another method of Optional i.e.
Optional<String> stringOptional=Optional.ofNullable(sample)
We will still need to check that
if(stringOptional.isPresent())
I dont understand and am not convinced, how is the above better than doing directly
if(sample!=null)
I know this question is purely opinion based, but would appreciate if someone points out and gives a good example of why optionals are a good addition to java and help developers not to write boiler-plate code.