Java 8 Clock equals() Method with Examples
Java Clock class is part of Date Time API, java.time.Clock, of Java. The Java Date Time API was added from Java version 8.
The equals() method of java.time.Clock class checks if two Clock objects are equal or not. If clocks are equal then it returns true, else it returns false. This equals method of clock class overrides this Object.equals(java.lang.Object) method to compare based on clock object state. If not overridden, then this equal() method takes the description of java.lang.Object.equals()
Syntax:
public boolean equals(Object obj)
Parameters: This method takes a mandatory parameter obj which is the clock object passed to compare with the existing clock object.
Return Value: This method returns true if two clocks objects are equal. Otherwise, it returns false.
Example:
Input:
Clock object of ZoneId "UTC"
Clock object of ZoneId "Asia/calcutta"
Output:
false
Explanation:
Both objects represent Clock object of the different zone.
Hence applying equals on them returns false.
Below programs illustrates equals() method of java.time.Clock class:
Program 1: When two similar class objects are compared.
Java
import java.time.Clock;
import java.time.ZoneId;
public class EqualsMethodDemo {
public static void main(String[] args)
{
Clock clock1 = Clock.system(ZoneId.of( "Etc/UTC" ));
System.out.println(clock1.toString());
Clock clock2 = Clock.systemDefaultZone();
System.out.println(clock2.toString());
boolean equalResponse = clock1.equals(clock2);
System.out.println( "Both clocks are equal:"
+ equalResponse);
}
}
|
Output:
SystemClock[Etc/UTC]
SystemClock[Etc/UTC]
Both clocks are equal:true
Program 2: When two different class objects are compared.
Java
import java.time.Clock;
import java.time.ZoneId;
public class EqualsMethodDemo {
public static void main(String[] args)
{
Clock clock1 = Clock.systemDefaultZone();
System.out.println( "clock1 Time Zone = "
+ clock1.getZone());
Clock clock2 = Clock.systemUTC();
System.out.println( "clock2 Time Zone = "
+ clock2.getZone());
boolean equalResponse = clock1.equals(clock2);
System.out.println( "Both clocks are equal:"
+ equalResponse);
}
}
|
Output:
clock1 Time Zone = Etc/UTC
clock2 Time Zone = Z
Both clocks are equal:false
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#equals-java.lang.Object-
Last Updated :
30 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...