MonthDay equals() method in Java

Java 8Object Oriented ProgrammingProgramming

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

A program that demonstrates this is given as follows

Example

 Live Demo

import java.time.*;
public class Main {
   public static void main(String[] args) {
      MonthDay md1 = MonthDay.parse("--02-22");
      MonthDay md2 = MonthDay.parse("--02-22");
      System.out.println("The MonthDay md1 is: " + md1);
      System.out.println("The MonthDay md2 is: " + md2);
      boolean flag = md1.equals(md2);
      if(flag)
         System.out.println("\nBoth MonthDay objects are equal");
      else
         System.out.println("\nBoth MonthDay objects are not equal");
   }
}

Output

The MonthDay md1 is: --02-22
The MonthDay md2 is: --02-22
Both MonthDay objects are equal

Now let us understand the above program.

The two MonthDay objects are displayed. It is checked if the MonthDay 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:

MonthDay md1 = MonthDay.parse("--02-22");
MonthDay md2 = MonthDay.parse("--02-22");
System.out.println("The MonthDay md1 is: " + md1);
System.out.println("The MonthDay md2 is: " + md2);
boolean flag = md1.equals(md2);
if(flag)
   System.out.println("\nBoth MonthDay objects are equal");
else
   System.out.println("\nBoth MonthDay objects are not equal");
raja
Published on 26-Mar-2019 11:02:37
Advertisements