Java:Language - Optionals

From Juneday education
Jump to: navigation, search

This is a short introduction to Optionals in Java - using the java.util.Optional<T> class to create objects that might be present or not.

Example - A Student might have an email address

Let's say we are using a Student class in some administration system handling student data.

A Student has a name and maybe an email.

So how do we represent the "maybe email"?

In previous, simplified, examples we've just let email be a String reference which will be null for Students without an email.

This is quite error-prone and should be avoided. Since Java 8 we have a solution to this problem. We can create "optional" objects. An Optional object is an object wrapped inside a java.util.Optional<T> object.

This wrapper lets us think about an object which either isPresent() or doesn't. If it isPresent(), we can get() the wrapped object. Also, you can use the orElse(...) method to provide a default value if the wrapped object doesn't exist.

To wrap the email String inside an Optional<String>, we use this.email = Optional.of(email).

If we wan't to handle the case of someone calling the constructor with null as the email, we can use this.email = Optional.ofNullable(email). If the email parameter is null, then this.email will become an empty optional.

Let's show some code to exemplify what an optional String for an email address looks like:

import java.util.Optional;

public class Student {

  private Optional<String> email;
  private String name;

  public Student(String name) {
    this.name = name;
    this.email = Optional.empty();
  }

  public Student(String name, String email) {
    this(name);
    this.email = Optional.of(email); // or: this.email = Optional.ofNullable(email);
  }

  public String name() {
    return name;
  }

  public Optional<String> email() {
    return email;
  }

  public String toString() {
    return (name + " " + email.orElse("")).trim();
  }
}

The interesting parts are:

  • The import statement
  • The declaration of the email variable
  • The constructors
  • The accessor method email()
  • The toString() method.

They all show the basics of using Optional objects.

Here's the client code and an example print-out:

public class StudentDemo {
  public static void main(String[] args) {
    Student aStudent = new Student("Charlie", "charlie@email.com");
    Student another = new Student("Bob");

    System.out.println(aStudent);
    System.out.println(another);
    
  }
}

/*
$ javac StudentDemo.java && java StudentDemo
Charlie charlie@email.com
Bob

*/

Let's look at it further from the client's perspective. With "client", we mean the code using our Student class.

public class StudentDemo {
  public static void main(String[] args) {
    Student aStudent = new Student("Charlie", "charlie@email.com");
    Student another = new Student("Bob");

    System.out.println(aStudent);
    System.out.println(another);

    if (another.email().isPresent()) {
      System.out.println("Here's the email for " + another.name() + ": "
                         + another.email().get());
    } else {
      System.out.println(another.name() + " doesn't have an email.");
    }
    
    if (aStudent.email().isPresent()) {
      System.out.println("Here's the email for " + aStudent.name() + ": "
                         + aStudent.email().get());
    } else {
      System.out.println(aStudent.name() + " doesn't have an email.");
    }
    
  }
}

/*
$ javac StudentDemo.java && java StudentDemo
Charlie charlie@email.com
Bob
Bob doesn't have an email.
Here's the email for Charlie: charlie@email.com
*/

Links

Source code

Where to go next

Next page has some exercises on Optionals.

The TOC (Table Of Contents) go to More_programming_with_Java#Java_Language

The Previous link is not decided yet and leads to the TOC for now.

« PreviousBook TOCNext »