Sitemap
Viraj Shetty

Viraj Shetty

Coder • Writer • Instructor • YouTube: https://www.youtube.com/@viraj_shetty • LinkedIn: https://www.linkedin.com/in/shettyviraj/

Member-only story

Java Optional — A Complete Guide

16 min readMay 30, 2024
Press enter or click to view image in full size
Photo by Fotis Fotopoulos on Unsplash

I regularly upload videos to my YouTube Channel at https://www.youtube.com/@viraj_shetty

Also check out my discounted Udemy Courses at https://www.mudraservices.com/courses/

In this article, I will explain everything about Java Optional in a concise manner with examples.

Part 1 — Java Optional Basics

Let’s take a look at the code below to see why Java’s Optional class was introduced in JDK 8.

public class Users {

public static User getUser(String uid) {
User user = null;

// logic to set user

return user;
}

}

// API Caller
User user = Users.getUser(uid);

// May throw NullPointerException
String name = user.name();

In the code, you see that there is a Users class (used as a User Factory class) which has a method to return a User object based on some logic (maybe fetching from the Database). The problem here is that, it’s perfectly possible for the user object to be null.

A standard way to use such a method is to call it and check if the user is null. If not null, then proceed to handle the user. If the null check was not in place (as in the code above), your application would throw a Null Pointer Exception. So, here’s a question ?

How can the programmer who…

--

--