Java 8 introduced a new class called Optional, which is a container object that may or may not contain a non-null value. The main purpose of the Optional class is to provide a way to handle null values in a more elegant and readable way than using traditional null checks. In this article, we will take a closer look at the Optional class and its methods, as well as provide examples of how to use it in your code.
The Optional class has several methods that can be used to work with its value, such as:
isPresent(): returns true if the Optional contains a non-null value, otherwise returns false.
get(): returns the value if it is present, otherwise throws a NoSuchElementException.
orElse(T other): returns the value if it is present, otherwise returns the provided value.
orElseGet(Supplier<? extends T> other): returns the value if it is present, otherwise returns the value provided by the given supplier.
orElseThrow(Supplier<? extends X> exceptionSupplier): returns the value if it is present, otherwise throws the exception provided by the given supplier.
Here’s an example of how you can use the Optional class to handle a null value:
public class OptionalExample { public static void main(String[] args) { String value = null; Optional<String> optionalValue = Optional.ofNullable(value); System.out.println(optionalValue.orElse("Default Value")); } }
In this example, we have a variable “value” that is set to null. We then create an Optional object using the “ofNullable” method and pass in the value. The “orElse” method is used to return a default value if the Optional object is empty.
here’s another example of how you can use the Optional class:
public class OptionalExample { public static void main(String[] args) { String value = "Hello World!"; Optional<String> optionalValue = Optional.ofNullable(value); optionalValue.ifPresent(val -> System.out.println("Value is: " + val)); } }
In this example, we have a variable “value” that is set to the string “Hello World!”. We then create an Optional object using the “ofNullable” method and pass in the value. The “ifPresent” method is used to check if the Optional object contains a value and if it does, it will print out the value to the console.
The output of this code will be:
Value is: Hello World!
The Optional class in Java 8 provides a lot of useful methods, ifPresent() is one of them, it is used to perform an action if a value is present, without the need to check for null values.In conclusion, The Optional class in Java 8 provides a more elegant way of handling null values in your code. It allows you to write more readable code and avoid the need for traditional null checks. It is a powerful tool that can be used to improve the quality of your code and make it more robust.
Keywords: Optional class, Java 8, null values, null checks, orElse, orElseGet, orElseThrow, NoSuchElementException, ofNullable.