Thursday, October 2, 2025
HomeLanguagesJavaPeriod negated() method in Java with Examples

Period negated() method in Java with Examples

The negated() method of Period class in Java is used to return a new instance of Period after negating all the elements of the period YEAR, MONTH, DAY.

Syntax:

public Period negated()

Parameters: This method does not accepts any parameter.

Return Value: This method returns a new instance of Period after negating each element of the period.

Exceptions: It throws an ArithmeticException. This exception is caught if numeric overflow occurs.

Below program illustrates the above method:

Program 1:




// Java code to show the function to negate all
// elements of the period
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodClass {
  
    // Function to negate given periods
    static void toNegate(Period p1)
    {
  
        System.out.println(p1.negated());
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Defining period
        int year = 4;
        int months = 11;
        int days = 10;
        Period p1 = Period.of(year, months, days);
  
        toNegate(p1);
    }
}


Output:

P-4Y-11M-10D

Program 2:




// Java code to show the function to negate all
// elements of the period
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodClass {
  
    // Function to negate given periods
    static void toNegate(Period p1)
    {
  
        System.out.println(p1.negated());
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Defining period
        int year = -4;
        int months = -11;
        int days = -10;
        Period p1 = Period.of(year, months, days);
  
        toNegate(p1);
    }
}


Output:

P4Y11M10D

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#negated–

RELATED ARTICLES

Most Popular

Dominic
32331 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11867 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11926 POSTS0 COMMENTS
Shaida Kate Naidoo
6818 POSTS0 COMMENTS
Ted Musemwa
7079 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS