devxlogo

Avoid NPE via JDK 8, Optional

Avoid NPE via JDK 8, Optional

Starting with JDK 8, you can avoid NullPointerException by returning an Optional. For example, instead of returning null, this method returns an empty Optional:

public Optional fetchShoppingCart(long id) {    ShoppingCart cart = // code that fetch the card content for the specified id    return Optional.ofNullable(cart);} 
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist