What is Period.equals() in Java?

equals() is an instance method of the Period class that is used to check the equality of the Period object with another Period object. The comparison is based on each of the three units and the Period type. The years, months, and days units must all be equal.

Note that a time of “24 months” is not the same as a period of “1 Year and 12 Months” or “2 Years”.

The equals() method is defined in the Period class. 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 boolean equals(Object obj)

Parameters

  • Object obj: The object to check.

Return value

This method returns true if the Period objects are equal. Otherwise, it returns false.

Code

In the below code, we use the equals() method to compare two different Period objects and print the result 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 period1 = Period.of(numYears, numMonths, numDays);
numYears = 5;
numMonths = 10;
numDays = 13;
Period period2 = Period.of(numYears, numMonths, numDays);
System.out.printf("(%s == %s) = %s\n", period1, period2, period1.equals(period2));
numYears = 5;
numMonths = 3;
numDays = 13;
Period period3 = Period.of(numYears, numMonths, numDays);
System.out.printf("(%s == %s) = %s\n", period1, period3, period1.equals(period3));
}
}

Free Resources