- 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
Java Integer compareTo() method
The java.lang.Integer.compareTo() method compares two Integer objects numerically. This method returns the value 0 if this Integer is equal to the argument Integer, a value less than 0 if this Integer is numerically less than the argument Integer and a value greater than 0 if this Integer is numerically greater than the argument Integer.
At first, set two Integer objects −
Integer obj1 = new Integer("100"); Integer obj2 = new Integer("200");
Now, compare those object −
int res = obj1.compareTo(obj2);
Following is an example to implement the compareTo() method in Java −
Example
public class Main { public static void main(String[] args) { Integer obj1 = new Integer("100"); Integer obj2 = new Integer("200"); int res = obj1.compareTo(obj2); if(retval > 0) { System.out.println("obj1 is greater than obj2"); } else if(retval < 0) { System.out.println("obj1 is less than obj2"); } else { System.out.println("obj1 is equal to obj2"); } } }
Output
obj1 is less than obj2
Advertisements