Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

optional
java
communitycreator

What is the Optional.of() method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In Java, an Optional object is a container object which may or may not contain a value. The Optional class is present in the java.util package.

Note: You can read more about the Optional class here.

What is the of() method of the Optional class?

The of() method is used to get an instance of the Optional class with the specified not-null value.

public static <T> Optional<T> of(T value)

Argument

  • value: This is the value which is to be present in the Optional object. value should not be null.

Return value

This method returns an Optional object with the specified value.

Code

The below code shows how to use the of() method:

import java.util.Optional;
  
class OptionalOfExample {
    public static void main(String[] args) {
        Optional<Integer> optional1 = Optional.of(1);
        System.out.println("Optional1 : " + optional1);

        Optional<String> optional2 = Optional.of("test");
        System.out.println("Optional2 : " + optional2);
    }
}

Explanation

In the above code:

  • In line 1, we import the Optional class.
import java.util.Optional;
  • In line 5, we use the of() method to get an Optional object of the Integer type with value 1.
Optional<Integer> optional1 = Optional.of(1);
optional1;// Optional[1]
  • In line 8, we use the of() method to get an Optional object of the String type with value test.
Optional<String> optional2 = Optional.of("test");
optional2;// Optional[test]

RELATED TAGS

optional
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring