For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
As Java developers, we frequently need to arrange items that are organized in a collection. Java enables us to apply different sorting algorithms to any kind of data. The Java compareTo method is essential in Java development and assists the developer in organizing complex objects and establishing custom sorting criteria. Without it, managing intricate objects becomes challenging. Therefore, it is an essential tool that every Java developer should possess in their toolkit.
As a component of the 'comparable' interface in Java, the 'compareTo' method establishes the natural ordering of objects in a class. By employing this approach, you can arrange or specify custom objects beneficially and clearly to minimize confusion and simplify development.
The CompareTo in Java is frequently utilized to sort collections and establish the relative sequence of objects by assessing their values. It's an essential component of the Comparable interface, permitting objects to be contrasted with one another.
Improve your Java programming skills with our Software Development courses — take the next step in your learning journey!
Below we discuss the Ins and Outs of CompareTo() function in Java. Keep on reading!
Prior to initiating a CompareTo in Java, it's essential to grasp several fundamental concepts and requirements. Here’s a list of information you ought to be aware of:
You need to be familiar with Java syntax, variables, and control structures, including loops and conditionals.
~ A negative integer if the current object is smaller than the argument object.
~ Zero if the present object matches the argument object.
~ A positive integer if the present object exceeds the argument object).
Also Read: Careers in Java: How to Make a Successful Career in Java in 2025
The method compareTo() evaluates two strings in a lexicographical manner. The comparison relies on the Unicode value assigned to each character within the strings.
The method yields 0 if the string matches the other string. A value below 0 is returned if the string has fewer characters than the other string, while a value above 0 is returned if the string has more characters than the other string.
public int compareTo(String string2)
public int compareTo(Object object)
Returns: An int value:
Also Read: What is Composition in Java With Examples
In Java, the compareTo() method allows for the lexicographical comparison of String objects (i.e., according to their Unicode values). The compareTo() function is specified in the Comparable interface, which is implemented by the String class. It examines two strings letter by letter and produces an integer outcome based on their lexicographic sequence.
int compareTo(String anotherString)
It evaluates the strings one character at a time, according to their Unicode values.
The comparison concludes when:
public class CompareToExample {
public static void main(String[] args) {
String str1 = "apple";
String str2 = "banana";
String str3 = "apple";
// Comparing str1 and str2
System.out.println("str1.compareTo(str2): " + str1.compareTo(str2)); // Negative value because "apple" is less than "banana"
// Comparing str1 and str3
System.out.println("str1.compareTo(str3): " + str1.compareTo(str3)); // 0 because both strings are equal
// Comparing str2 and str1
System.out.println("str2.compareTo(str1): " + str2.compareTo(str1)); // Positive value because "banana" is greater than "apple"
}
}
Output:
str1.compareTo(str2): -1
str1.compareTo(str3): 0
str2.compareTo(str1): 1
Explanation:
In Java, you can utilize the compareTo() method to compare wrapper classes such as Integer, Double, and additional numeric wrappers. These wrapper classes implement the Comparable<T> interface, enabling them to be compared with one another through the compareTo() method.
Both of these classes implement the Comparable<T> interface, which means they possess a compareTo() method that can be utilized to compare their values.
int compareTo(T anotherObject)
Where T is the type of the object (e.g., Integer, Double, etc.).
public class IntegerCompare {
public static void main(String[] args) {
Integer num1 = 5;
Integer num2 = 10;
Integer num3 = 5;
// Comparing num1 and num2
System.out.println("num1.compareTo(num2): " + num1.compareTo(num2)); // Negative, 5 < 10
// Comparing num1 and num3
System.out.println("num1.compareTo(num3): " + num1.compareTo(num3)); // 0, 5 == 5
// Comparing num2 and num1
System.out.println("num2.compareTo(num1): " + num2.compareTo(num1)); // Positive, 10 > 5
}
}
Output:
num1.compareTo(num2): -1
num1.compareTo(num3): 0
num2.compareTo(num1): 1
Explanation:
public class DoubleCompare {
public static void main(String[] args) {
Double d1 = 5.5;
Double d2 = 10.5;
Double d3 = 5.5;
// Comparing d1 and d2
System.out.println("d1.compareTo(d2): " + d1.compareTo(d2)); // Negative, 5.5 < 10.5
// Comparing d1 and d3
System.out.println("d1.compareTo(d3): " + d1.compareTo(d3)); // 0, 5.5 == 5.5
// Comparing d2 and d1
System.out.println("d2.compareTo(d1): " + d2.compareTo(d1)); // Positive, 10.5 > 5.5
}
}
Output:
d1.compareTo(d2): -1
d1.compareTo(d3): 0
d2.compareTo(d1): 1
Explanation:
Explanation:
Also Read: Transient in java: What is, How Does it Work?
To create the compareTo() method in a custom class in Java, you should adhere to these steps:
public class MyClass implements Comparable<MyClass> {
@Override
public int compareTo(MyClass other) {
// Comparison logic
}
}
Let’s define a basic class Person that includes attributes for name and age. We will define compareTo() to ensure that Person objects are compared according to their age.
Step-by-Step Code:
public class Person implements Comparable<Person> {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
// Overriding the compareTo() method to compare by age
@Override
public int compareTo(Person other) {
// Compare ages (this.age - other.age)
return Integer.compare(this.age, other.age);
}
// toString() method for better output
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
public static void main(String[] args) {
// Create some Person objects
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Bob", 25);
Person person3 = new Person("Charlie", 30);
// Compare the persons
System.out.println(person1.compareTo(person2)); // Positive because 30 > 25
System.out.println(person1.compareTo(person3)); // Zero because 30 == 30
System.out.println(person2.compareTo(person1)); // Negative because 25 < 30
}
}
Explanation:
Class Implementation: The Person class realizes the Comparable<Person> interface.
compareTo() Function:
We assess two Person objects by their age attribute.
The Integer.compare(this.age, other.age) function is utilized to reliably compare the ages, guaranteeing that the outcome aligns with the agreement of compareTo().
toString() Method: This is implemented to offer a clearer output when displaying Person objects.
Output:
5
0
-5
In Java, the compareTo() method compares objects, which is crucial for sorting objects in collections or arrays. The compareTo() function is included in the Comparable<T> interface, and when a class implements it, it establishes the natural order of that class's objects.
By implementing the CompareTo in Java, it can automatically utilize it for sorting, including using the Collections.sort() method for List instances or the Arrays.sort() method for arrays.
int compareTo(T other)
T represents the type of the object under comparison (such as String, Integer, or any user-defined class).
The other is the item being contrasted with the current item (this).
To sort custom objects with compareTo(), the class needs to implement the Comparable<T> interface and override the compareTo() method. For instance, let's define a class Person in which we will assess objects based on their age.
Example: Sorting Person Objects by Age
import java.util.*;
class Person implements Comparable<Person> {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
// Implementing compareTo to compare by age
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age); // Compare ages
}
// toString() method for easy output
@Override
public String toString() {
return name + " (" + age + ")";
}
public static void main(String[] args) {
// Create a List of Person objects
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
people.add(new Person("David", 28));
// Sort the list using compareTo() (which compares by age)
Collections.sort(people);
// Output the sorted list
System.out.println("Sorted by age:");
for (Person person: people) {
System.out.println(person);
}
}
}
Explanation of the Example:
Person class: The class Person implements the Comparable<Person> interface, which means we must define the compareTo() method.
compareTo() method:
We evaluate Person objects based on their age by utilizing Integer.compare(this.age, other.age).
Integer.compare(a, b) offers a more reliable method for comparing two integers, yielding:
Sorting:
We generate a List<Person> and include multiple Person objects.
We utilize Collections.sort(people) to arrange the list, and Java will invoke the compareTo() method to establish the sequence of the elements in the list according to their age.
toString() method: We customize the toString() function to deliver a unique string format for every Person, simplifying the process of printing the object.
Output:
Sorted by age:
Bob (25)
David (28)
Alice (30)
Charlie (35)
Comparable | Comparator |
Comparable is an interface in Java. | Comparator is a functional interface in Java. |
Comparable provides a compareTo() method to sort objects. | The comparator provides a compare() method to sort objects. |
Comparable is a part of the Java.lang package. | Comparator is a part of the java.util package. |
Comparable can be used for natural or default ordering. | A comparator can be used for custom ordering. |
Comparable provides a single sorting sequence. Ex: Sort either by id or name | The comparator provides multiple sorting sequences. Ex. Sort by both id and name. |
Comparable modifies the class that implements it. | The comparator doesn't modify any class. |
class Person implements Comparable<Person> {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age); // Compare based on age
}
@Override
public String toString() {
return name + " (" + age + ")";
}
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
Collections.sort(people); // Uses compareTo() to sort by age
System.out.println(people); // [Bob (25), Alice (30), Charlie (35)]
}
}
import java.util.*;
class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
// Using Comparator to sort by name
people.sort(new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName()); // Sort by name alphabetically
}
});
System.out.println(people); // [Alice (30), Bob (25), Charlie (35)]
}
}
When utilizing the compareTo() method or Comparator in Java, managing null values and edge cases is essential for maintaining robustness and avoiding errors. Here are several recommended methods for managing these situations:
Null values can be challenging when comparing objects since they lack a natural order. To prevent NullPointerException, it's essential to explicitly manage null values in your comparison logic.
Handling Null in compareTo()
When creating the compareTo() method within the Comparable interface, it's crucial to think about how to handle scenarios where one of the objects being compared is null. Typically, you cannot invoke methods on null, so it is essential to manage it correctly.
Typical Approach:
Example:
class Person implements Comparable<Person> {
private String name;
private Integer age;
// Constructor
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
// Overriding compareTo() to compare by age, handling null
@Override
public int compareTo(Person other) {
if (other == null) {
return 1; // Consider this object greater if the other is null
}
// Null check for the 'age' field itself
if (this.age == null && other.age == null) {
return 0; // Both null, they are equal
}
if (this.age == null) {
return -1; // This object is less because the age is null
}
if (other.age == null) {
return 1; // Other object is less because the age is null
}
return Integer.compare(this.age, other.age); // Normal comparison
}
@Override
public String toString() {
return name + " (" + age + ")";
}
public static void main(String[] args) {
Person p1 = new Person("Alice", 30);
Person p2 = new Person("Bob", null);
Person p3 = new Person("Charlie", 25);
List<Person> people = Arrays.asList(p1, p2, p3);
Collections.sort(people);
System.out.println(people); // Sorting with null handling
}
}
Dealing with Null in Comparator
When utilizing a Comparator, you can directly manage null values in the comparison logic within the compare() method.
Typical Approach:
You can utilize Comparator.nullsFirst() or Comparator.nullsLast() from the Comparator utility class to manage null values reliably.
Example with Comparator:
import java.util.*;
class Person {
private String name;
private Integer age;
// Constructor
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public Integer getAge() {
return age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
public static void main(String[] args) {
Person p1 = new Person("Alice", 30);
Person p2 = new Person("Bob", null);
Person p3 = new Person("Charlie", 25);
List<Person> people = Arrays.asList(p1, p2, p3);
// Comparator with null handling: nullsLast sorts nulls at the end
people.sort(Comparator.comparing(Person::getAge, Comparator.nullsLast(Integer::compareTo)));
System.out.println(people); // Sorting with null handling
}
}
Case 1: Equal Objects
When two items are identical, the compareTo() function is expected to return 0. Make sure this situation is addressed properly by your compareTo() or Comparator method.
Example:
@Override
public int compareTo(Person other) {
if (this.age == null && other.age == null) {
return 0; // Both null ages are considered equal
}
return Integer.compare(this.age, other.age); // If ages are the same, return 0
}
Case 2: Sorting in Reverse Order
At times, you may prefer to arrange in reverse order (from highest to lowest). You have the option to change the comparison logic or utilize Comparator.reversed().
Example:
people.sort(Comparator.comparing(Person::getAge).reversed()); // Sort in descending order
Case 3: Handling Comparable with Multiple Fields
If you possess items with various attributes (e.g., name and age), you might want to take both attributes into account for sorting. You can use compareTo() to compare based on the primary field and then revert to secondary fields in the event of ties.
Example: Sorting by age, then by name:
@Override
public int compareTo(Person other) {
int ageComparison = Integer.compare(this.age, other.age);
if (ageComparison != 0) {
return ageComparison;
}
return this.name.compareTo(other.name); // If ages are the same, compare names
}
1: What is the function of the compareTo() method in Java?
A: The compareTo() function is included in the Comparable<T> interface, which serves to establish the natural ordering of objects. It enables the comparison of objects for the sake of sorting.
2: What occurs if two objects are equivalent in compareTo()?
A: If two items are deemed equivalent, the compareTo() method must return 0. This indicates that the items hold identical value when assessed with the established natural ordering principles.
3: How does compareTo() differ from Comparator?
A: The compareTo() method facilitates natural ordering and is specified in the Comparable<T> interface. It must be carried out within the class itself.
A comparator is an outside interface utilized to establish personalized sorting behavior. It is helpful when you need to arrange objects in various manners or when you lack control over the class (i.e., you are unable to alter the class to include Comparable).
4: What occurs when you mistakenly implement compareTo()?
A: If compareTo() isn't implemented properly, it may lead to:
5: What is the definition of compareTo()?
A: The compareTo() function is required to follow this contract:
To sort students by marks using compareTo(), you must define a Student class and implement the Comparable<Student> interface. Next, implement the compareTo() method to evaluate students according to their scores.
Here’s a detailed implementation process:
Code Implementation:
import java.util.*;
public class Student implements Comparable<Student> {
private String name;
private int marks;
// Constructor to initialize name and marks
public Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
// Getter methods for name and marks
public String getName() {
return name;
}
public int getMarks() {
return marks;
}
// Implement compareTo to compare students by marks
@Override
public int compareTo(Student other) {
// Compare by marks in ascending order
return Integer.compare(this.marks, other.marks);
}
// Override toString method for better display
@Override
public String toString() {
return name + " (" + marks + " marks)";
}
// Main method to test sorting of students
public static void main(String[] args) {
// Create a list of students
List<Student> students = Arrays.asList(
new Student("Alice", 85),
new Student("Bob", 92),
new Student("Charlie", 78),
new Student("David", 95)
);
// Sort the students by marks in ascending order
Collections.sort(students);
// Print the sorted list of students
System.out.println("Sorted students by marks:");
for (Student student : students) {
System.out.println(student);
}
}
}
Explanation:
Attributes:
name: The name of the student.
marks: The marks obtained by the student.
compareTo() Method:
The compareTo() function evaluates students according to their scores.
It Returns:
Sorting:
Output
The students' list will be organized by their grades in increasing order (standard function of compareTo()).
Sorted students by marks:
Charlie (78 marks)
Alice (85 marks)
Bob (92 marks)
David (95 marks)
To change the compareTo() method for sorting employees based on experience, you must create an Employee class containing pertinent attributes (like name and experience), implement the Comparable<Employee> interface, and override the compareTo() method to evaluate employees according to their experience.
Here’s how you can alter it:
Code Implementation:
import java.util.*;
public class Employee implements Comparable<Employee> {
private String name;
private int experience; // Experience in years
// Constructor to initialize name and experience
public Employee(String name, int experience) {
this.name = name;
this.experience = experience;
}
// Getter methods for name and experience
public String getName() {
return name;
}
public int getExperience() {
return experience;
}
// Implement compareTo to compare employees by experience
@Override
public int compareTo(Employee other) {
// Compare by experience in ascending order
return Integer.compare(this.experience, other.experience);
}
// Override toString method for better display
@Override
public String toString() {
return name + " (" + experience + " years experience)";
}
// Main method to test sorting of employees
public static void main(String[] args) {
// Create a list of employees
List<Employee> employees = Arrays.asList(
new Employee("Alice", 5),
new Employee("Bob", 10),
new Employee("Charlie", 2),
new Employee("David", 7)
);
// Sort the employees by experience in ascending order
Collections.sort(employees);
// Print the sorted list of employees
System.out.println("Sorted employees by experience:");
for (Employee employee : employees) {
System.out.println(employee);
}
}
}
Explanation:
Attributes:
name: The name of the employee.
experience: The number of years of experience the employee has.
compareTo() Method:
This method compares employees based on their experience.
It returns:
Sorting:
Collections.sort() is used to sort the list of employees. Since Employee implements Comparable<Employee>, the compareTo() method is called during the sorting process to order employees by experience.
Output:
The employees will be sorted by their experience in ascending order.
Sorted employees by experience:
Charlie (2 years experience)
Alice (5 years experience)
David (7 years experience)
Bob (10 years experience)
To arrange products in descending order by price utilizing a Comparator, you must first establish a Product class, and then either create an independent Comparator class or apply a lambda expression for sorting by price in descending order.
Steps:
Code Implementation:
import java.util.*;
// Product class with name and price attributes
class Product {
private String name;
private double price;
// Constructor to initialize name and price
public Product(String name, double price) {
this.name = name;
this.price = price;
}
// Getter methods for name and price
public String getName() {
return name;
}
public double getPrice() {
return price;
}
// Override toString method for better display
@Override
public String toString() {
return name + " ($" + price + ")";
}
}
// Comparator to sort products by price in descending order
class PriceDescendingComparator implements Comparator<Product> {
@Override
public int compare(Product p1, Product p2) {
// Compare prices in descending order
return Double.compare(p2.getPrice(), p1.getPrice()); // Reverse the order for descending
}
}
public class Main {
public static void main(String[] args) {
// Create a list of products
List<Product> products = Arrays.asList(
new Product("Laptop", 1200.99),
new Product("Smartphone", 799.49),
new Product("Headphones", 199.99),
new Product("Tablet", 399.99)
);
// Sort products by price in descending order using the Comparator
Collections.sort(products, new PriceDescendingComparator());
// Print the sorted list of products
System.out.println("Products sorted by price (descending):");
for (Product product : products) {
System.out.println(product);
}
}
}
Explanation:
Product Class:
PriceDescendingComparator Class:
Sorting:
The method Collections.sort() is utilized to arrange the list of products in order. It accepts the list and the comparator (PriceDescendingComparator) as parameters.
Output:
Products will be sorted by their price in descending order
Products sorted by price (descending):
Laptop ($1200.99)
Smartphone ($799.49)
Tablet ($399.99)
Headphones ($199.99)
The CompareTo in Java is an effective method for evaluating strings or Integer instances. It enables developers to establish the lexicographic or numerical sequence of two values. By grasping its behavior and usage, programmers can efficiently arrange and organize data according to certain criteria.
It offers an easy method to apply comparison logic and facilitate informed decision-making in Java programming. You can explore courses and tutorials at upGrad to understand what compare() is in Java and how to utilize it.
upGrad’s courses offer expert training in Java programming, focusing on the abs() method, performance optimization, and best practices. Gain hands-on experience in handling numerical computations, managing absolute values efficiently, and building high-performance Java applications.
Below are some relevant upGrad courses:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
In Java, the compareTo method serves to compare two objects of identical type and establish their relative sequence, returning a negative integer when the current object is lesser than the compared one, zero if they are equivalent, and a positive integer if the current object exceeds the compared object; effectively establishing the "natural order" for object comparison within a class.
In Java, the compareTo method belongs to the Comparable interface, which is implemented by several core Java classes such as String, Integer, Double, and Character. This implementation means these classes possess a built-in compareTo method, enabling natural ordering comparisons among objects of that type.
The compareTo() method accepts another object of the same type as an argument and returns an integer that signifies the relative ordering of the two objects. The potential return values include: A negative integer if the current object is smaller than the argument object.
When two strings match, the compareTo method yields a result of 0. The compareTo method assesses strings lexicographically, and if they match, it signifies equality by returning 0. A positive number is returned when the first string is "greater than" the second, and a negative number when the first string is "less than" the second.
The compareToIgnoreCase() function compares two strings in a lexicographical manner, disregarding differences between uppercase and lowercase characters. The comparison relies on the Unicode value of every character in the string after being changed to lowercase. The function gives back 0 if the string matches the other string, disregarding case variations.
The compareTo() method in Java will throw a NullPointerException when attempting to compare an object with a null object.
Evaluates two Strings to determine if one precedes or follows the other, or if they are identical. The strings are examined character by character, utilizing the ASCII values of the characters. This indicates that, for instance, 'a' is positioned before 'b' but after 'A'.
compareTo: Evaluates two strings in lexicographic order. equals: Checks if this string is equal to the given object. CompareTo assesses two strings based on their characters (at matching indices) and returns an integer that can be positive or negative based on the comparison.
When a class implements Comparable, it overrides the compareTo() method to define how instances of that class should be compared. The method yields: — A negative integer if the current object is smaller than the specified object. — Zero if the current object matches the specified object.
In Java, by implementing the Comparable interface, a class indicates that it establishes a natural order for its instances, enabling direct sorting using methods such as Collections.sort() without needing an additional comparator, effectively determining how instances of that class ought to be compared during sorting.
The compareTo() function in Java evaluates objects and establishes their comparative sequence. It provides an integer result for the comparison. It is frequently utilized for arranging and organizing items.
12. Can the compareTo method be used for case-insensitive comparisons?
CompareTo and Compare(String, String) functions. They each carry out a case-sensitive comparison.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.