I have a question regarding Java 8\'s Optional, the purpose of which is to tackle NullPointerException
exceptions.
The question is, what is the reason for h
Code example: Optional.of()
VS Optional.ofNullable()
@Test
public void TestOptional() {
String message = "Hello World!";
System.out.println("message -> " + message + "\n");
Optional genderOptional = Optional.of(message);
System.out.println("Optional.of(message) -> " + genderOptional);
System.out.println("Optional.of(message).get() -> " + genderOptional.get());
try {
Optional.of(null);
} catch (java.lang.NullPointerException e) {
System.out.println("Optional.of(null) -> java.lang.NullPointerException \n");
}
System.out.println("Optional.empty() -> " + Optional.empty() + "\n");
System.out.println("Optional.ofNullable(null) -> " + Optional.ofNullable(null));
System.out.println("Optional.ofNullable(message) -> " + Optional.ofNullable(message));
System.out.println("Optional.ofNullable(message).get() -> " + Optional.ofNullable(message).get());
}
Output:
message -> Hello World!
Optional.of(message) -> Optional[Hello World!]
Optional.of(message).get() -> Hello World!
Optional.of(null) -> java.lang.NullPointerException
Optional.empty() -> Optional.empty
Optional.ofNullable(null) -> Optional.empty
Optional.ofNullable(message) -> Optional[Hello World!]
Optional.ofNullable(message).get() -> Hello World!