[Java] NullPointerException countermeasure example of Java 8 or later (Optional)

1 minute read

About this article

I have found a new way to deal with NullPointerException in Java8, so I will write it as a memorandum.

Event

I will put out a lukewarm immediately.

java



public class Test {
public static void main(String[] args) {
String str = null;
System.out.print(str.length());
}
}

processing result


Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:6)

I got a NullPointerException. As a workaround implemented from java8, by adding Optional NullPointer can be dealt with. Change it with the image below.

Coping example


import java.util.Optional;

public class Test {

public static void main(String[] args) {
String str = null;
// System.out.print(str.length());
It's a sequel.
Optional<String> strOpt = Optional.ofNullable(str);
strOpt.ifPresent(v -> System.out.println(v.length()));
}
}

NullPointerException did not occur and the processing ended successfully-

Brief commentary

Optional is implemented in java8 or later https://docs.oracle.com/javase/jp/8/docs/api/java/util/Optional.html

Optional<String> strOpt = Optional.ofNullable(str);

You can use ofNullable() function by wrapping str with Optional like this. As an argument of the ifPresent function, Once, save the contents of str to variable v and use it in Systemoutpintline Such a method is called a lambda expression and is a new feature implemented from java8 together with Optional.

strOpt.ifPresent(v -> System.out.println(v.length()));
  • Article summarizing lambda expressions https://engineer-club.jp/java-lambda-expression

By the way, a useless example that uses isPresent and get()… (Added July 31, 2020)

Initially I wrote the following example as a different pattern, but the following method seems to be a ** worthy workaround ** I will put it as a bad example with a commandment to myself. You can see it by reading this article https://qiita.com/BlueRayi/items/ef46496ef2ef36b9cbb7#%E3%81%AA%E3%82%8B%E3%81%B9%E3%81%8Foptionalifpresent%E3%82%82%E4%BD%BF %E3%81%86%E3%81%AA (* From the beginning of this article, it seems that Null check using Optional is nonsense.)

Bad example


import java.util.Optional;

public class Test {
public static void main(String[] args) {
String str = null;
// System.out.print(str.length());
It's a sequel.
Optional<String> strOpt = Optional.ofNullable(str);
if(strOpt.isPresent()) {
String message = strOpt.get();
System.out.println(message.length());
}
}
}

Specifically, the method of using isPresent() in the if statement to get() its value can be implemented easily. The isPresent() function is often used when it is unavoidable without taking advantage of using Optional, and the following article seems to be nuancedly easy to understand.

You should rarely use >get.

The purpose of using Optional is to say “Please do nothing if no value is entered”. If you get a sudden exception using >get, it’s the same as throwing a NullPointerException.

https://irof.hateblo.jp/entry/2015/05/05/071450