Java8 – Optional’s Overview with Examples


Java8 – Optional’s Overview with Examples

We can reduce the chance of NullPointerException’s in Java using best practices –

  • Don’t return null’s from methods
  • Don’t pass null’s as arguments

You can also use java.lang.Optional. Java8 Optional formalises the approach used in other languages, and already existed in some Java libraries. Optional is simply an object wrapper.


My approach is similar style to my post Java8 – Streams Cookbook and have included a class with a number of examples using Optional

Here is our base model, without getters and setters -

class Bike {
    private Optional<Wheels> wheels;
    private String brand;
    public Bike(Optional<Wheels> wheels, String brand) {
        this.wheels = wheels;
        this.brand = brand;

class Wheels {
    private String brand;
    private int spokes;
    public Wheels(String brand, int spokes) {
        this.brand = brand;
        this.spokes = spokes;
class NoBikeException extends Exception {
	private static final long serialVersionUID = 1L;

Empty Optionals

  • Empty optional using Optional.empty()
  • NoSuchElementException
  • ifPresent, orElse, ifPresent, orElseThrow method

Null Objects In Optionals

  • of - Populate with null object - Throws Exception
  • ofNullable - allows null

Values In Optionals

  • Filtering and mapping in combination with Lambdas
  • flatMap to prevent Optional<Optional>

If you have liked this post, check out my personal blog which contains similar tutorials at

Create your playground on
This playground was created on, our hands-on, knowledge-sharing platform for developers.
Go to