Tuesday, February 14, 2023

Optional in java (Avoid NullPointerException)

Optional in java

Package java.util.Optional

In Java, the Optional class is a container object which may or may not contain a non-null value. It's part of the Java Standard Library and was introduced in Java 8.

The purpose of Optional is to provide a clear way to represent the presence or absence of a value in a way that makes it easier to write code that avoids null pointer exceptions. It's designed to be used as a return type for methods that may or may not return a value.

Here's a basic example of how to use Optional in Java:

import java.util.Optional; public class OptionalExample { public static void main(String[] args) { Optional<String> optional = Optional.of("Hello, World!"); System.out.println(optional.isPresent()); // Outputs: true System.out.println(optional.get()); // Outputs: Hello, World! Optional<String> emptyOptional = Optional.empty(); System.out.println(emptyOptional.isPresent()); // Outputs: false } }

The Optional.of(value) method creates a new Optional instance with the specified non-null value. If you try to create an Optional instance with a null value, a NullPointerException will be thrown.

The Optional.empty() method creates a new empty Optional instance.

You can use the isPresent() method to check if an Optional instance contains a value. If it does, you can use the get() method to retrieve the value. If the Optional is empty, the get() method will throw a NoSuchElementException.

You can also use the orElse(defaultValue) method to get the value of an Optional instance, or a default value if the Optional is empty. For example:

Optional<String> optional = Optional.empty(); String value = optional.orElse("defaultValue"); System.out.println(value); // Outputs: defaultValue

There are other methods available in the Optional class, such as orElseGet(Supplier), orElseThrow(Supplier), ifPresent(Consumer), etc., that allow you to handle the absence or presence of a value in a variety of ways.


Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home