Created
December 22, 2021 12:48
-
-
Save arsalankhan994/5f01c8a4a8f354bd95add48667e5410e to your computer and use it in GitHub Desktop.
Handle Null Objects - Java
This file contains hidden or 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
public class HandleNullObjectJava { | |
public static void main(String[] args) { | |
String object = "Erselan Khan"; | |
String nullObject = null; | |
// Accessing both objects | |
/* | |
First Start with non-null object | |
*/ | |
boolean value = object.equals("Erselan Khan"); | |
System.out.println("value: " + value); | |
/* | |
1. Handle null object using try/catch | |
*/ | |
try { | |
nullObject.equals("Erselan Khan"); | |
} catch (NullPointerException exception) { | |
System.out.println("NullPointerException"); | |
} | |
/* | |
2. Handle null object using if check | |
*/ | |
if (nullObject != null) { | |
System.out.println("nullObject: " + nullObject); | |
} else { | |
System.out.println("nullObject is null"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment