What is Period.plusYears() in Java?
plusYears() is an instance method of the Period class that is used to add the specified number of years. The months and days units are unaffected.
The plusYears() method is defined in the Period class. The Period class is defined in the java.time package. To import the Period class, use the following import statement:
import java.time.Period;
Syntax
public Period plusYears(long yearsToAdd)
Parameters
yearsToAdd: The number of years to add. This parameter can be positive or negative.
Return value
This method returns a new instance of the Period class with the number of years added.
Code
In the below code, we add three years to the basePeriod object with the help of the plusYears() method and print the new object to the console.
import java.time.Period;public class Main{public static void main(String[] args) {int numYears = 5;int numMonths = 10;int numDays = 13;// Define a period objectPeriod basePeriod = Period.of(numYears, numMonths, numDays);// number of days to addint yearsToAdd = 3;// New Period object after the additionPeriod newPeriod = basePeriod.plusYears(yearsToAdd);System.out.printf("%s + %s years = %s", basePeriod, yearsToAdd, newPeriod);System.out.println();}}