0% found this document useful (0 votes)
2 views7 pages

Java Optional

Java 8 introduced Optional<T>, a container object that helps avoid NullPointerExceptions by explicitly handling the presence or absence of values. It encourages clearer contracts and safer access patterns, promoting a functional programming style. Developers can create, access, and transform Optionals using various methods, enhancing code readability and reducing runtime errors.

Uploaded by

surajahilya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Java Optional

Java 8 introduced Optional<T>, a container object that helps avoid NullPointerExceptions by explicitly handling the presence or absence of values. It encourages clearer contracts and safer access patterns, promoting a functional programming style. Developers can create, access, and transform Optionals using various methods, enhancing code readability and reducing runtime errors.

Uploaded by

surajahilya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

🎯JAVA Optional<T>

The End of NullPointerException Begins Here

Say goodbye to NullPointerException—and hello


to intentional design.

In traditional Java, handling null has been


both a necessity and a common source of runtime
errors.

With Java 8, Optional<T> redefines how


developers think about the presence or absence
of a value ....
Optional<T> (java.util.Optional)

Optional<T> is a container object introduced in Java 8


that may or may not contain a non-null value. It's used
to avoid NullPointerException and make null checks explicit
and safe.

 Why Use Optional<T>?


Traditionally, returning null from methods can cause:
 Null pointer exceptions
 Hidden bugs
 Unclear intent
Optional<T> encourages:
 Clearer contracts (maybe has a value)
 Functional programming style (map, filter, etc.)
 Safer access patterns

#p.k.prusty https://lnkd.in/givxjG-A www.linkedin.com/in/pkprusty999 @codetechtone


🔧 Creating Optionals
Method Description
Optional.of(value) Creates an Optional with a non-null value.
Throws NullPointerException if value is null.
Optional.ofNullable(value) Creates an Optional that may be null.
Optional.empty() Creates an empty Optional.

Optional<String> name = Optional.of("John");


Optional<String> maybeNull = Optional.ofNullable(possiblyNullValue);
Optional<String> none = Optional.empty();

🔍 Accessing Values
1. isPresent(), get()
if (name.isPresent())
{
System.out.println(name.get());
}

⚠️ get() is risky if the value is not present. Avoid in favor of


safer alternatives below.

#p.k.prusty https://lnkd.in/givxjG-A www.linkedin.com/in/pkprusty999 @codetechtone


2. ifPresent(Consumer<? super T>)

Executes a lambda only if value is present:


name.ifPresent(n -> System.out.println(n.toUpperCase()));

3. orElse(T other)

Returns the value if present, otherwise returns a default:


String result = name.orElse("Default Name");

4. orElseGet(Supplier<? extends T>)

Like orElse() but lazily calls a Supplier only if needed


String result = name.orElseGet(() -> computeDefaultName());

5. orElseThrow()
Throws NoSuchElementException if value not present:
String result = name.orElseThrow();

String result = name.orElseThrow(() -> new IllegalArgumentException("No name!"));

#p.k.prusty https://lnkd.in/givxjG-A www.linkedin.com/in/pkprusty999 @codetechtone


🔁 Transforming Values

1. map(Function<T, R>)
Applies a function if value is present and wraps the result:
Optional<String> upper = name.map(String::toUpperCase);

2.flatMap(Function<T, Optional<R>>)
Same as map, but does not wrap nested Optionals:
Optional<User> user = Optional.of(userRepo)
.flatMap(repo -> repo.findById("123")); // returns Optional<User>

3. filter(Predicate<T>)
Filters value based on a condition:
Optional<String> result = name.filter(n -> n.startsWith("J"));
Example:
Before: User user = repo.findById("123");
if (user != null) {
return user.getName();
}
return "Unknown";

After: String name = repo.findById("123")


.map(User::getName)
.orElse("Unknown");

Before: User user = repo.findById("123");


if (user != null && user.getProfile() != null) {
return user.getProfile().getEmail();
}
return "Email not available";

After: return Optional.ofNullable(repo.findById("123"))


.map(User::getProfile)
.map(Profile::getEmail)
.orElse("Email not available");

#p.k.prusty https://lnkd.in/givxjG-A www.linkedin.com/in/pkprusty999 @codetechtone


Follow
https://lnkd.in/givxjG-A

www.linkedin.com/in/pkprusty999

#p.k.prusty https://lnkd.in/givxjG-A www.linkedin.com/in/pkprusty999 @codetechtone

You might also like