Skip to main content


Showing posts from September, 2021

Null Check In Java

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 With introduction of `Optional` class in Java 8, we can use it to perform actions on an object if its value is not null. public void java8Optional(String s) { Optional.ofNullable(s) .ifPresent((str) -> { //do something System.out.println("String is not null"); }); } Java 9 Java 9 enhances the Optional class to provide an els