Skip to content

Instantly share code, notes, and snippets.

@viveknaskar
Created October 22, 2020 20:09
Show Gist options
  • Save viveknaskar/930e6b92282139755ca76e072ccda84f to your computer and use it in GitHub Desktop.
Save viveknaskar/930e6b92282139755ca76e072ccda84f to your computer and use it in GitHub Desktop.
Example to avoid NullPointerException using Optional
package com.viveknaskar;
import java.util.Optional;
public class ExampleWithOptional {
public static void main(String[] args) {
String[] cities = new String[10];
/**
* Using Optional class, we are doing a null check at cities[5]
*/
Optional<String> nullCheck = Optional.ofNullable(cities[5]);
if (nullCheck.isPresent()) {
String city = cities[5].toLowerCase();
System.out.print(city);
} else {
System.out.println("The array is null");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment