- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MonthDay compareTo() method in Java
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
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("
The first MonthDay object is greater than the second MonthDay object"); else if(val < 0) System.out.println("
The first MonthDay object is lesser than the second MonthDay object"); else System.out.println("
The 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("
The first MonthDay object is greater than the second MonthDay object"); else if(val < 0) System.out.println("
The first MonthDay object is lesser than the second MonthDay object"); else System.out.println("
The MonthDay objects are equal");
Advertisements