# Period equals() method in Java

Java 8Object Oriented ProgrammingProgramming

The equality of two Periods can be determined using the equals() method in the Period class in Java. This method requires a single parameter i.e. the Period object to be compared. Also it returns true if both the Period objects are equal and false otherwise.

A program that demonstrates this is given as follows

## Example

Live Demo

import java.time.Period;
public class Demo {
public static void main(String[] args) {
String period1 = "P5Y7M15D";
Period p1 = Period.parse(period1);
String period2 = "P5Y7M15D";
Period p2 = Period.parse(period2);
System.out.println("The Period p1 is: " + p1);
System.out.println("The Period p2 is: " + p2);
boolean flag = p1.equals(p2);
if(flag)
System.out.println("\nBoth Period objects are equal");
else
System.out.println("\nBoth Period objects are not equal");
}
}

## Output

The Period p1 is: P5Y7M15D
The Period p2 is: P5Y7M15D
Both Period objects are equal

Now let us understand the above program.

The two Period objects are displayed. It is checked if the Period objects are equal using the equals() method. The returned value of the method is displayed using an if statement. A code snippet that demonstrates this is as follows:

String period1 = "P5Y7M15D";
Period p1 = Period.parse(period1);
String period2 = "P5Y7M15D";
Period p2 = Period.parse(period2);
System.out.println("The Period p1 is: " + p1);
System.out.println("The Period p2 is: " + p2);
boolean flag = p1.equals(p2);
if(flag)
System.out.println("\nBoth Period objects are equal");
else
System.out.println("\nBoth Period objects are not equal");
Updated on 30-Jul-2019 22:30:25