Last active
August 16, 2021 09:07
-
-
Save rabestro/37687d0f9e1f86c49eaaa67814d6dc13 to your computer and use it in GitHub Desktop.
Optional.isNull(obj) vs obj == null
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
import java.util.Scanner; | |
import java.util.Objects; | |
public class Main | |
{ | |
public static void main(String[] args) { | |
Object obj = null; | |
if (obj == null) { | |
// This is the best way to check for null (KISS) | |
} | |
if (Objects.isNull(obj)) { | |
} | |
} | |
// The advantage of using Objects.isNull | |
static void someMethod() { | |
// In case, you are checking if boolean variable is null or not. | |
// You can make typo as below. | |
var obj = Boolean.TRUE; | |
if (obj = null) { // typo | |
// It compiles without error but here will be NPE at runtime | |
} | |
if (Objects.isNull(obj)) { | |
// It runs correctly | |
} | |
// if obj is other type then error at compile type | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment