Java has evolved over the years. Below are few of the methods to check whether an object is Null or not in Java.
Java 5
Before Java 8 we were able to check for an object being Null by using a simple `if` statement, as shown in code below:
public void preJava8(String s) {
if (s == null) {
// do something
System.out.println("String is null");
}
System.out.println("String is not null");
}
Java 8
public void java8Optional(String s) {
Optional.ofNullable(s)
.ifPresent((str) -> {
//do something
System.out.println("String is not null");
});
}
Java 9
public void java9Optional(String s) {
Optional.ofNullable(s)
.ifPresentOrElse(
(str) -> {
//do something
System.out.println("String is not null");
},
() -> {
//do something
System.out.println("String is null");
});
}