Optional Class
In Java, the Optional class was introduced in Java 8 to handle null values and avoid NullPointerExceptions. It provides a way to encapsulate an optional value.
To create an Optional object, you can use the static methods of() and ofNullable(). The of() method expects a non-null value, while the ofNullable() method can accept both null and non-null values.
Here's an example:
1import java.util.Optional;
2
3public class Main {
4
5 public static void main(String[] args) {
6 String name = null;
7 Optional<String> optionalName = Optional.ofNullable(name);
8
9 if (optionalName.isPresent()) {
10 System.out.println("Name: " + optionalName.get());
11 } else {
12 System.out.println("Name is not present");
13 }
14 }
15
16}In this example, we have a variable name that is null. We create an Optional object, optionalName, using the ofNullable() method. We can then use the isPresent() method to check if a value is present in the Optional object, and the get() method to retrieve the value.
If the value is present, we print it as "Name: [value]", otherwise, we print "Name is not present".
By using the Optional class, we can handle null values more gracefully and avoid NullPointerExceptions. It encourages a more explicit and safer coding style by forcing the developer to check for the presence of a value before using it.
xxxxxxxxxximport java.util.Optional;public class Main { public static void main(String[] args) { String name = null; Optional<String> optionalName = Optional.ofNullable(name); if (optionalName.isPresent()) { System.out.println("Name: " + optionalName.get()); } else { System.out.println("Name is not present"); } }}


