Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
plusyears
period

What is Period.plusYears() in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 object
Period basePeriod = Period.of(numYears, numMonths, numDays);
// number of days to add
int yearsToAdd = 3;
// New Period object after the addition
Period newPeriod = basePeriod.plusYears(yearsToAdd);
System.out.printf("%s + %s years = %s", basePeriod, yearsToAdd, newPeriod);
System.out.println();
}
}

RELATED TAGS

java
communitycreator
plusyears
period

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring