Java Duration Class | negated() Method with Example

Duration Class negated() method: Here, we are going to learn about the negated() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 16, 2020

Duration Class negated() method

  • negated() method is available in java.time package.
  • negated() method is used to represent the negated value of this Duration.
  • negated() method is a non-static method, it is accessible with class object only and if we try to access the method with class name then we will get an error.
  • negated() method may throw an exception at the time of returning negated value.
    ArithmeticException: This exception may throw when the calculated result value exceeds the limit.

Syntax:

    public Duration negated();

Parameter(s):

  • None

Return value:

The return type of this method is Duration, it returns the Duration that holds the negated value of this Duration.

Example:

// Java program to demonstrate the example 
// of negated() method of Duration

import java.time.*;

public class NegatedOfDuration {
    public static void main(String args[]) {
        // Instantiates two Duration objects
        Duration du1 = Duration.ofHours(-10);
        Duration du2 = Duration.parse("P2DT2H2M");

        // Display du1 and du2
        System.out.println("du1: " + du1);
        System.out.println("du2: " + du2);

        // returns the negated length
        // of this Duration du1
        Duration negated_val = du1.negated();
        System.out.println("du1.negated(): " + negated_val);

        // returns the negated length
        // of this Duration du2
        negated_val = du2.negated();
        System.out.println("du2.negated(): " + negated_val);
    }
}

Output

du1: PT-10H
du2: PT50H2M
du1.negated(): PT10H
du2.negated(): PT-50H-2M


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.