Instant equals() method in Java

Java 8Object Oriented ProgrammingProgramming

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

A program that demonstrates this is given as follows

Example

 Live Demo

import java.time.*;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      Instant i1 = Instant.parse("2019-01-13T16:10:35.00Z");
      Instant i2 = Instant.parse("2019-01-13T16:10:35.00Z");
      System.out.println("Instant object i1 is: " + i1);
      System.out.println("Instant object i2 is: " + i2);
      boolean flag = i1.equals(i2);
      if(flag)
         System.out.println("\nThe Instant objects are equal");
      else
         System.out.println("\nThe Instant objects are not equal");
   }
}

Output

Instant object i1 is: 2019-01-13T16:10:35Z
Instant object i2 is: 2019-01-13T16:10:35Z
The Instant objects are equal

Now let us understand the above program.

The two instant objects i1 and i2 are displayed. It is checked if the Instant 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:

Instant i1 = Instant.parse("2019-01-13T16:10:35.00Z");
Instant i2 = Instant.parse("2019-01-13T16:10:35.00Z");
System.out.println("Instant object i1 is: " + i1);
System.out.println("Instant object i2 is: " + i2);
boolean flag = i1.equals(i2);
if(flag)
   System.out.println("\nThe Instant objects are equal");
else
   System.out.println("\nThe Instant objects are not equal");
raja
Published on 27-Mar-2019 10:04:46
Advertisements