Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
Ravi Vishwakarma
24-Apr-2025In Java,
null
is often used to represent the absence of a value. However, this can lead to problems likeNullPointerException
if not handled properly.Java 8 introduced the
Optional<T>
class injava.util
to provide a better way to model optional (nullable) values.1. What is
Optional<T>
?Optional<T>
is a container object that may or may not contain an unknown value.If any value is present then
isPresent()
returnstrue
andget()
returns value.2. Creating Optional Instances
3. Common Optional Methods
isPresent()
ifPresent(Consumer)
orElse(T)
orElseGet(Supplier)
orElseThrow()
NoSuchElementException
if value is absentmap(Function)
flatMap(Function)
4. Examples
a. Safe Access
b. Execute If Present
c. Avoid NullPointerException
Instead of:
With
Optional
:d. Using
orElseGet()
andorElseThrow()
5. When to Use Optional
Good for:
null
checksAvoid:Optional
is used in real-world APIs or want to convert anull
-prone method to useOptional
.