Interview Questions — Optional in Java

Uğur Taş
Codimis
Published in
6 min readSep 27, 2023

--

Java interview questions — Java Optional

Java introduced the Optional class in Java 8 as part of the java.util package. It provides a more eloquent way to deal with cases that may or may not produce a value, thus helping to handle the absence of value situations without null references. Since its inception, Optional has been frequently used as a return type for methods, emphasizing that the method might not always return a meaningful value.

In this article, we’ll discuss some of the commonly asked interview questions related to Java Optionals, along with their short answers.

If you don’t have a medium membership, you can use this link to reach the article without a paywall.

1. What is Java Optional?

Optional is a container object that may or may not contain a non-null value. If a value is present, Optional.isPresent() returns true and Optional.get() returns the value. Otherwise, isPresent() returns false and get() throws a NoSuchElementException.

2. Why was Optional introduced?

--

--

Uğur Taş
Codimis

A software developer with a high passion for learning, improving skills, and sharing knowledge. My motto is “fail million times if you take lessons every time”