Skip to content

Instantly share code, notes, and snippets.

@rabestro
Last active August 16, 2021 09:07
Show Gist options
  • Save rabestro/37687d0f9e1f86c49eaaa67814d6dc13 to your computer and use it in GitHub Desktop.
Save rabestro/37687d0f9e1f86c49eaaa67814d6dc13 to your computer and use it in GitHub Desktop.
Optional.isNull(obj) vs obj == null
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