Duration abs() method in Java


An immutable copy of duration can be obtained using the abs() method in the Duration class in Java. This method requires no parameters and it returns the immutable copy of the duration. Also, if a numeric overflow occurs the ArithmeticException is thrown.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.Duration;
public class GFG {
   public static void main(String[] args) {
      Duration d = Duration.ofHours(1);
      System.out.println("The duration is: " + d);
      System.out.println("A copy of the above duration is: " + d.abs());
   }
}

Output

The duration is: PT1H
A copy of the above duration is: PT1H

Now let us understand the above program.

An immutable copy of the duration is obtained using the abs() method. Then this is displayed. A code snippet that demonstrates this is as follows −

Duration d = Duration.ofHours(1);
System.out.println("The duration is: " + d);
System.out.println("A copy of the above duration is: " + d.abs());

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements