Created
October 22, 2020 20:09
-
-
Save viveknaskar/930e6b92282139755ca76e072ccda84f to your computer and use it in GitHub Desktop.
Example to avoid NullPointerException using Optional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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