Java 9 java.util.Objects Additions

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

1. Introduction

The java.util.Objects class has been part of Java since version 1.7. This class provides static utility methods for objects which can be used to perform some of the everyday tasks like checking for equality, null checks, etc.

In this article, we will look at the new methods introduced in the java.util.Objects class in Java 9.

2. The requireNonNullElse Method

This method accepts two parameters and returns the first parameter if it is not null, the second parameter otherwise. If both parameters are null, it throws NullPointerException:

3. Using requireNonNullElseGet

This method is similar to requireNonNullElse, except that the second parameter, is a java.util.function.Supplier interface which allows a lazy instantiation of the provided collection. The Supplier implementation is responsible for returning a non-null object as shown below:

Note: In mathematics, a range represented in the form of [a, b) indicates the range is inclusive of a and exclusive of b. [ and ] state that the number is included and ( and ) state that the number is excluded.

6. Using checkFromIndexSize

This method is similar to checkFromToIndex except that instead of providing the upper bound of the sub-range we provide the size and the lower bound of the sub-range.

The sub-range, in this case, is [fromIndex, fromIndex + size) and this method checks that the sub range is within the range formed by [0, length):