Code Pumpkin

What is optional and why it is there? | Java8

October 29, 2017
Posted by Pumpkin
Subscribe

Have you ever been tired of putting null checks all over the code to avoid any unnecessary NullPointerExceptions. Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications. The Optional is a wrapper class which makes a field optional which means it may or may not have values. By doing that, It improves the readability because the fact which was earlier hidden in the code is now obvious to the client.

Advantage of Java8  Optional:

  • Optional: Null checks are not required.
  • No more Boilerplate code
  • No more NullPointerException at run-time.
  • Clean and neat APIs can be developed

The catch with this new Optional class is, of course, the word "class". Optional is only a wrapper that contains a reference to some other object and isn't close to being a panacea for NullPointerExceptions.

Let's see, an example of how we can create and use optional:

There are many ways to create Optional

To create optional with non-null values you can write as below:


Employee employee = new Employee(); 
Optional<Employee> op = Optional.of(employee); 

To create optional with an empty value you can write as below:


Optional<Employee> employee = Optional.empty(); 

Now, let's make use of the optional to avoid NullPointerException .

With out Optional:



if (project != null) {
    ApplicationType applicationType = project.getApplicationType();
    if (applicationType != null) {
        String typeDirName = applicationType.getTypeDirName();
        if (typeDirName != null) {
            System.out.println(typeDirName);
        }
    }
}

now with optional we can re-write above code using optional and streams 😉


Optional<String> optionalTypeDirName = optionalProject
        .flatMap(project -> project.getApplicationTypeOptional())
        .flatMap(applicationType -> applicationType.getTypeDirNameOptional());
optionalTypeDirName.ifPresent(typeDirName -> System.out.println(typeDirName));

Even I can see some of the disadvantages of using Optional:

  • Not serializable making it useless for many cases.
  • Optional is a wrapper which means if you use it you'll now have two object references where you used to have one.
  • In Some cases, it makes the debugging even worse nightmare.

That is all for Optional now. To explore some more java8 feature you can check this article: Java8 features.

Some of the good to know features are: Lambda ExpressionsFunctional Interfaces

Some articles you would like to go through:

Further Reading For Interview Preparation:

  1. String Pool
  2. interface VS abstract class
  3. Wrapper Classes – Autoboxing and Unboxing,  IntegerCache and Immutability
  4. How To Create Immutable Class In Java
  5. CountDownLatch Vs CyclicBarrier
  6. What is the use of private constructor in java?

Happy Learning smiley

Tags: , , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.

Total Post : 80
Subscribe
Contribute Your Articles

Interview Experiences

Related Books

Like Us On Facebook

Alexa Page Rank