Java Optional Example

By | | Updated : 2021-03-12 | Viewed : 237 times

Java Optional Example

In this article, we will be focusing on Java 8 Optional Example. Let's get started to learn Java 8 Optional with examples.

Java 8 Optional

One of the important features introduced in Java 8 is the Optional. When writing Java code, objects is a primary necessity of programming. Sometimes objects do not have any values which will be represented as null. If the object is null then it causes abnormal termination with unexpected exceptions such as NullPointerException. Inside of Optional these null objects will be wrapped up. So Optional behaves as a wrapper of null that means it is the container of null objects. And where these null objects can be handled properly using Optional.

Creating Optional In Java 8

The optional class allows creating Optional Object using three methods. Those are of(), ofNullable() and empty(). We will be looking at all these methods one by one.

Now it's time to create Optional objects for wrapping with other objects. Let's take a look at the below-given classes.

Please find below given classes as example classes to explain Optional class methods.

Author class for Optional in java
public class Author {
	private Book book;
	private string authorName;
}
Book class for Optional in java
public class Book {
	private string bookName;
}

Now we will be looking at different methods and how these methods are useful for the creation of the Optional class.

of()

The Optional class of() is one way of creating an optional class. in of(), the argument that means object reference should not be null. In case if it is null then of() method throws the NullPointerException.

of() in Optional Java 8
Author author = new Author();
Optional<Author> author = Optional.of(author);

Notice the above-given code snippet. If the author is null then of() method would throw the NullPointerException.

ofNullable()

ofNullable() is used to create Optional object. When we need an object with null in java then ofNullable() is preferable as it allows null valued objects.

ofNullable() in Optional Java 8
Author author = null;
Optional<Author> author = Optional.ofNullable(author);

Notice author reference has passed as null. ofNullable() method can take null as an argument.

empty()

The third approach to create an Optional object is empty(). It creates the Optional object as container which contains empty object.

empty() in Optional Java 8
Optional<Author> author= Optional.empty();

So far, we have learned how to create the Optional class object. Sometimes We would need to check the optional whether the Optional class contains an object or not. For that Optional class provide different types of methods. We will take a look at these all methods.

isPresent()

One of the best advantages of the Options class is that the Optional class allows avoiding null checks in Java programming. Please see how can we achieve this using isPresent() method.

Null checks Without Optional
// Without Optional
Book book = author.getBook();
if (book != null) {
    System.out.println(book.getName());
} else {
    System.out.printn("Author does not have printed book.");
}
Null checks With Optional
// With Optional
Optional<Book> book = Optional.ofNullable(author.getBook());
if (book.isPresent()) {
    System.out.println(book.getName());
} else {
    System.out.println("Author does not have printed book.");
}

Notice the above-given code snippet, it is possible to avoid the null checks using with isPresent() method which is a good approach to handle the null checks introduced in Java 8.

ifPresent()

Notice below the code snippet used for checking the object is existed or not in the Optional class.

ifPresent() in Optional Java 8
Optional<Book> book = Optional.ofNullable(author.getBook());
book.ifPresent(System.out::println);

It is an advanced option to check the value is presented or not. We can avoid the checks over here. If you see the isPresent() method it is required to check the optional container whether the object has existed or not with value.

isEmpty()

This is another optional method to check the Optional class contains a value object or not. Here it gives whether the object empty or not as like as isPresent() method.

isEmpty() in Optional Java 8
Optional<Book> book = Optional.ofNullable(author.getBook());
if (book.isEmpty()) {
    System.out.println("The book is not printed.");
} else {
    //As book existed can be applicable for operations.
}

If the object is null then it is required to create an alternate object or need to have another option. It is possible with Optional. We will look into this.

orElse()

If Optional does not contain an object then another object can be created. Notice below given example.

orElse() in Optional Java 8
Author author= author.orElse(new Author("William Shakespeare"));

orElseGet()

orElseGet() is used same as orElse() method. But here we can use a lambda expression to create an alternative object when the object is empty.

orElseGet() in Optaional Java 8
Author author = author.orElseGet(() -> new Author("William Shakespeare"));

orElseThrow()

When an object in Optional is null or does not exist then it is required to throw an exception. orElseThrow() is the right method in Optional in java 8 for this case.

orElseThrow() in Optional Java 8
Author author = author.orElseThrow(NoAuthorFoundException::new);

To conclude this article, the Optional class is used to avoid null checks and NullPointerException. of(), ofNullable() and empty() methods are useful for creating the Optional. And we can use different types of methods (isPresent(), ifPresent() and isEmpty()) to check the object is existed or not in Optaional. There are other methods to get an allternate object to incase the object is empty.

Leave A Reply