What is Period.of() in Java?

Definition

The of() method is a static method of the Period class, which is used to get an instance of the same class representing the number of years, months, and days. The Period class is defined in the java.time package.

To import the Period class, check the following import statement:

import java.time.Period;

Syntax

public static Period of(int years, int months, int days)

Parameters

  • int years: The number of years. It can be positive or negative.
  • int months: Number of months. It can be positive or negative.
  • int days: Number of days. It can be positive or negative.

Return value

The method returns an instance of the Period class.

Code

We create two Period class objects with positive and negative parameters in the code below. Then, we print the objects 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;
Period period = Period.of(numYears, numMonths, numDays);
System.out.println("Positive parameters - " + period);
numYears = -5;
numMonths = -10;
numDays = -13;
period = Period.of(numYears, numMonths, numDays);
System.out.println("Negative parameters - " + period);
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources