Duration isNegative() method in Java


It can be checked if the duration is negative or not using the isNegative() method in the Duration class in Java. This method requires no parameters. Also, it returns true if the duration is negative 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.ofSeconds(5);
      boolean flag = d.isNegative();
      System.out.println("The duration is: " + d);
      if(flag)
         System.out.println("The above duration is negative");
      else
         System.out.println("The above duration is not negative");
   }
}

Output

The duration is: PT5S
The above duration is not negative

Now let us understand the above program.

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

Duration d = Duration.ofSeconds(5);
boolean flag = d.isNegative();
System.out.println("The duration is: " + d);
if(flag)
System.out.println("The above duration is negative");
else
System.out.println("The above duration is not negative");

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements