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;
public static Period of(int years, int months, int days)
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.The method returns an instance of the Period
class.
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);}}