How to create an Optional from existing Object in Java?

If you have an existing Object in Java that you want to convert to type Optional then you can make use of the of() or ofNullable() static methods from the Optional class.

import java.util.Optional;

public class Example {

    public static void main(String[] args) {

        String strObject1 = "Coe2care";
        Optional optionalValue1 = Optional.of(strObject1);

        String strObject2 = null;
        Optional optionalValue2 = Optional.ofNullable(strObject2);

        if (optionalValue1.isPresent()) {
            System.out.println("Value: " + optionalValue1.get());
        } else {
            System.out.println("Value is null");

        if (optionalValue2.isPresent()) {
            System.out.println("Value: " + optionalValue2.get());
        } else {
            System.out.println("Value is null");



Value: Coe2care
Value is null

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap