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 else condition to ifPresent() method of Optional in Java 8.
        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");
                            });
        }
    

Full code can be found in our Github repository.

0 comments:

Post a Comment