What is DurationUtils.zeroIfNull() in Java?

Overview

zeroIfNull() is a staticthe methods in Java that can be called without creating an object of the class. method of the DurationUtils that returns the passed Duration object if it is non-null. Otherwise, it returns Duration.ZERO.

What is Duration.ZERO?

Duration.ZERO is a Duration object with zero seconds and zero nanoseconds.

How to import DurationUtils

The definition of DurationUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to 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.

You can import the DurationUtils class as follows:


import org.apache.commons.lang3.time.DurationUtils;

Syntax


public static Duration zeroIfNull(final Duration duration)

Parameters

  • final Duration duration: The duration object to check.

Return value

This method returns the given duration object if the object is non-null. Otherwise, it returns Duration.ZERO.

Code

import org.apache.commons.lang3.time.DurationUtils;
import java.time.Duration;
public class Main{
public static void main(String[] args) {
// Example 1
Duration duration = Duration.ofDays(3);
System.out.printf("DurationUtils.zeroIfNull(%s) = %s", duration, DurationUtils.zeroIfNull(duration));
System.out.println();
// Example 2
duration = null;
System.out.printf("DurationUtils.zeroIfNull(%s) = %s", duration, DurationUtils.zeroIfNull(duration));
}
}

Example 1

  • Duration = PT72H

The method returns PT72H, i.e., the passed object because the passed Duration object is non-null.

Example 2

  • Duration = null

The method returns PT0S because the passed Duration object is null.

Output

The output of the code will be as follows:


DurationUtils.zeroIfNull(PT72H) = PT72H
DurationUtils.zeroIfNull(null) = PT0S
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources