DEV Community

Chaitanya Chunduri
Chaitanya Chunduri

Posted on

Handle Null like a pro using Optional

Many times we think that our code is perfect, works like a charm in the given scenarios and we proceed for deployment in production on a fine Friday. But when the code hits production due to unexpected data or due to some failure, when the code throws NullPointerExcpetion, the feeling comes like damn this weekend also ha...

But Thank God, we have a rescuer to fight with NPE(NullPointerException) who came into the existence since Java 8 which is Optional class.

In this article let us find out how we can use Optional in day to day jobs.

To create Optional object we have two methods,

  1. using of method
  2. using ofNullable

Here are the examples

Optional<String> optional = Optional.of("Chaitanya");
Optional<String> opNullable = Optional.ofNullable("Chaitanya");
Enter fullscreen mode Exit fullscreen mode

If you think that there is a possibility of null coming because of the calling function then you can use ofNullable.

of method throws NPE if the value is null, so, if you're certain that you don't get a null value you can use of method.

IMO, for simple operations like variable initialization or you've simple values and you want to pass them then you can use of method, if you're calling some external function for the result then you can use ofNullable.

Optional is something like a container that holds a value. To get things out of the container we need to open it, same way to get the value out of the Optional, we've get method.

Optional<String> optional = Optional.of("Chaitanya");
System.out.println(optional.get());
Enter fullscreen mode Exit fullscreen mode

Think that you got a big container, you opened it and found nothing, then you feel disappointed right? To save from these kinds of bad feelings, we have isPresent method, usage is like this.

Optional<String> nameOptional = getFirstName();
if(nameOptional.isPresent()) {
  System.out.println(nameOptional.get());
} else {
  System.out.println("No Name :( ");
}
Enter fullscreen mode Exit fullscreen mode

If you want to handle in a functional style, here is the way

nameOptional.ifPresent(value -> {
  System.out.println(value);
});
Enter fullscreen mode Exit fullscreen mode

or using method references

nameOptional.ifPresent(System.out::println);
Enter fullscreen mode Exit fullscreen mode

Sometimes we don't want to do anything when an exception raises, without Optional one way is we return null in catch block, but from Optional we've one more method empty(), here is the usage:

try {
  return Optional.ofNullable(getEmpName());
} catch (Exception ex) {
 return Optional.empty();
}
Enter fullscreen mode Exit fullscreen mode

Sometimes we may need to manipulate the results of certain operations, in such cases, we've map and flatMap methods

Optional<String> nameInUpperCaseOptional =                            
                       Optional.ofNullable(getEmpName())
                          .map(String::toUpperCase)
                          .get();
Enter fullscreen mode Exit fullscreen mode

Here map returns one more Optional object with the transformed value. If you want to get direct value instead of Optional object, then you can use flatMap method.

String nameInUpperCase = Optional.ofNullable(getEmpName())
                          .flatMap(String::toUpperCase);
Enter fullscreen mode Exit fullscreen mode

If you want to return a default value when there is no value present, you can use orElse

String EMPTY = "";
String name = Optional.ofNullable(getEmpName())
                  .orElse(EMPTY);
Enter fullscreen mode Exit fullscreen mode

If you want to perform some action when there is no value present, you can use orElseGet

String name = Optional.ofNullable(getEmpName())
                  .orElseGet(_ -> System.out.println("There is no Value :( "));
Enter fullscreen mode Exit fullscreen mode

If you want to throw an exception when there is no value present then we've orElseThrow

String name = Optional.ofNullable(getEmpName())
                  .orElseThrow(Exception::new);
Enter fullscreen mode Exit fullscreen mode

In Java 11, There are some more enhancements in Optional class like ifPresentElse, or, stream, here is the link to documentation for further details. Java 11#Optional

That is it for this article :) If you use Optional properly you can pretty much avoid NPE and can avoid stressful weekends too.

Thanks for spending time. I appreciate your feedback.

Top comments (0)