MonthDay compareTo() method in Java

Java 8Object Oriented ProgrammingProgramming

Two MonthDay objects can be compared using the compareTo() method in the MonthDay class in Java. This method requires a single parameter i.e. the MonthDay object to be compared.

If the first MonthDay object is greater than the second MonthDay object it returns a positive number, if the first MonthDay object is lesser than the second MonthDay object it returns a negative number and if both the MonthDay objects are equal it returns zero.

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("--05-15");
      System.out.println("The first MonthDay object is: " + md1);
      System.out.println("The second MonthDay object is: " + md2);
      int val = md1.compareTo(md2);
      if(val > 0)
         System.out.println("\nThe first MonthDay object is greater than the second MonthDay object");
      else if(val < 0)
         System.out.println("\nThe first MonthDay object is lesser than the second MonthDay object");
      else
         System.out.println("\nThe MonthDay objects are equal");
   }
}

Output

The first MonthDay object is: --02-22
The second MonthDay object is: --05-15

The first MonthDay object is lesser than the second MonthDay object

Now let us understand the above program.

First the two MonthDay objects are displayed. Then they are compared using the compareTo() method and the result is displayed using if else statement. A code snippet that demonstrates this is as follows:

MonthDay md1 = MonthDay.parse("--02-22");
MonthDay md2 = MonthDay.parse("--05-15");
System.out.println("The first MonthDay object is: " + md1);
System.out.println("The second MonthDay object is: " + md2);
int val = md1.compareTo(md2);
if(val > 0)
   System.out.println("\nThe first MonthDay object is greater than the second MonthDay object");
else if(val < 0)
   System.out.println("\nThe first MonthDay object is lesser than the second MonthDay object");
else
   System.out.println("\nThe MonthDay objects are equal");
raja
Published on 26-Mar-2019 10:58:21
Advertisements