Using Optional to Avoid NullPointerException in Java


Optional is a container object which may or may not contain a non-null value. Use it to avoid NullPointerException.

Source Code

Optional optionalString = Optional.ofNullable(null);
String result = optionalString.orElse("Default String");
System.out.println(result); // Outputs "Default String"
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments