The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.

Member-only story

Playing With Java Optional

--

Photo by Kristopher Roller on Unsplash

A container object which may or may not contain a non-null value

Introduction

During your life as a Java developer, you have surely encountered a NullPointerException. Read on if this is the exception you encounter the most. I imagine you might be thinking something like, “Yes, I agree, NullPointerExceptions is a pain for any Java developer, novice or expert, but there’s not much we can do about them.“ This is a common feeling in the programming world. Until Java 8 introduced Optional.

Optional allows an object to wrap those nullable values. The intention is to finally give us the ability to express a type for the returned value more clearly.

Instead of using a Java annotation, which is not checked at compile-time, Optional allows you to boost your methods and indicate that your method probably returns “empty” (and not null) values.

The NullPointerException problem

Before diving into the usage of Optional, let’s understand what issue it promises to resolve. When we create a java application, we will surely use method chaining to de-reference object properties, which can…

--

--

The Startup
The Startup

Published in The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.

Sofiene Ben Khemis
Sofiene Ben Khemis

Written by Sofiene Ben Khemis

Software Engineer & AWS Community Builder I’m not perfect. still running after my dreams. going to the moon 🌑

Responses (3)