Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
equals
period

What is Period.equals() 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.

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));
}
}

RELATED TAGS

java
communitycreator
equals
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