defaultIfNull() is a ObjectUtils that returns the default value if the passed object is null.
ObjectUtilsWe can find the definition of ObjectUtils in the Apache Commons Lang package, and add it to the Maven project using the following dependency in the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
We can import the ObjectUtils class as follows:
import org.apache.commons.lang3.ObjectUtils;
public static <T> T defaultIfNull(final T object, final T defaultValue)
final T object: The object to check for null.
final T defaultValue: The default value to return.
This return value method returns the default value if the object points to null. Otherwise, it returns the passed object.
import org.apache.commons.lang3.ObjectUtils;public class Main {public static void main(String[] args) {Object object = 1.234;String defaultValue = "defaultvalue";System.out.printf("The output of ObjectUtils.defaultIfNull() for the string - '%s' is %s", object, ObjectUtils.defaultIfNull(object, defaultValue));System.out.println();object = null;System.out.printf("The output of ObjectUtils.defaultIfNull() for the string - '%s' is %s", object, ObjectUtils.defaultIfNull(object, defaultValue));System.out.println();}}
object = 1.234defaultValue = "defaultvalue"The method returns 1.234 because the object is not null.
object = nulldefaultValue = "defaultvalue"The method returns defaultvalue because the object is null.
The output of the code is follows:
The output of ObjectUtils.defaultIfNull() for the string - '1.234' is 1.234
The output of ObjectUtils.defaultIfNull() for the string - 'null' is defaultvalue