# Java Optional class

In 
Published 2022-12-03

This tutorial explains to you how to use Java Optional class.

The Optional class was introduced in Java 8. It is a public final class and used to deal with NullPointerException. If you want to use this class you must import java.util package.

This class has various methods to check if there is any value in class instance and which is the value for that variable.

Please take a look at the following example and read carefully the comments. The code is self-explanatory.

When the base application was downloaded from Spring Initializr, I added the Car class and I updated the main class as below:

Car.java
package com.example.demo;

public class Car {
    String carNumber;
    String type;

    public Car(String carNumber, String type) {
        this.carNumber = carNumber;
        this.type = type;
    }

    public String getNumber() {
        return carNumber;
    }

    public void setNumber(String carNumber) {
        this.carNumber = carNumber;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Car{" +
                "carNumber='" + carNumber + '\'' +
                ", type='" + type + '\'' +
                '}';
    }
}
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Optional;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {

		SpringApplication.run(DemoApplication.class, args);

        Car car1 = new Car("DDD 783", "Audi");

		// We have nothing in this string
		String string1 = null;

		// "of" method is used when we are working with variable which are not empty
		Optional<Car> oCar1 = Optional.of(car1);

		// "ofNullable" method is used when we are working with variable which are empty
		Optional<String> oString1 = Optional.ofNullable(string1);

		//Test if car1 instance is empty
		if (oCar1.isPresent()) {
			System.out.println("car1 is not empty");
		}

		if (!oString1.isPresent()) {
			System.out.println("oString1 is empty");
		}

		string1 = "now string1 gets a value";

        // test if "oString1" is empty
		if (oString1.isPresent()) {
			System.out.println("NOW, oString1 is NOT empty");
		} else {
			System.out.println("NOW, oString1 is empty");
		}

        // "get()" method return the instance of the object, Optional class contains
		System.out.println("The number of the car is = " + oCar1.get().getNumber());

		System.out.println("Application stopped.");
	}
}

When I run the code, I get :

car1 is not empty
oString1 is empty
NOW, oString1 is empty
The number of the car is =DDD 783
Application stopped.

Process finished with exit code 0

More information you have here.