Duration isZero() method in Java

Java 8Object Oriented ProgrammingProgramming

It can be checked if the duration is of zero length or not using the isZero() method in the Duration class in Java. This method requires no parameters. Also, it returns true if the duration is of zero length and false otherwise.

A program that demonstrates this is given as follows −

Example

Live Demo

import java.time.Duration;
public class Demo {
public static void main(String[] args) {
Duration d = Duration.ofHours(1);
boolean flag = d.isZero();
System.out.println("The duration is: " + d);
if(flag)
System.out.println("The above duration is of zero length");
else
System.out.println("The above duration is not of zero length");
}
}

Output

The duration is: PT1H
The above duration is not of zero length

Now let us understand the above program.

First the duration is displayed. Then flag holds the returned value of isZero() method. According to the value in flag, the length of the duration is zero or not and that is printed. A code snippet that demonstrates this is as follows −

Duration d = Duration.ofHours(1);
boolean flag = d.isZero();
System.out.println("The duration is: " + d);
if(flag)
System.out.println("The above duration is of zero length");
else
System.out.println("The above duration is not of zero length");
Updated on 30-Jul-2019 22:30:25