Example
compareTo() Method
If str1 > str2, a positive value is returned.
If str1 < str2, a negative value is returned.
If str1 == str2, the result is 0.
Program:
Java
public class compareToExample {
public static void main(String args[]) {
String s1 = "Strings are immutable";
String s2 = new String("Coding Ninjas is amazing");
String s3 = new String("Strings are immutable");
int result = s1.compareTo( s2 );
System.out.println(result);
result = s1.compareTo( s3 );
System.out.println(result);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
16
0
compareTo() with Empty String
When we compare two strings, and one of them is empty, the function returns the length of the second string. So, if the first string is empty, the method returns a negative, and if the second string is empty, the method returns a positive integer equal to the first string's length.
Program:
Java
public class compareToExample {
public static void main(String args[]) {
String str1="coding";
String str2="";
String str3="me";
System.out.println(str1.compareTo(str2));
System.out.println(str2.compareTo(str3));
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
6
-2
Also check out String Args in Java
compareTo() case sensitive
To see if the compareTo() function takes case sensitivity into account, we'll compare two strings with the same letters in the same order. Consider two strings, one with uppercase characters and the other with lowercase letters. When comparing these two strings, if the result is 0, the compareTo() function ignores the case sensitivity of characters; otherwise, the method takes case sensitivity into account.
Program:
Java
public class compareToExample {
public static void main(String args[]) {
String str1 = new String("CODING NINJAS");
String str2 = new String("coding ninjas");
System.out.println(str1.compareTo(str2));
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
-32
compareTo() ClassCastException
When objects of incompatible types are compared, the ClassCastException is produced.
Program:
Java
import java.util.*;
class Players
{
private String name;
public Players(String str)
{
name = str;
}
}
public class CompareToExample4
{
public static void main(String[] args)
{
Players coding = new Players("Coding");
Players ninjas = new Players("Ninjas");
Players workdone = new Players("Workdone");
ArrayList<Players> al = new ArrayList<>();
al.add(coding);
al.add(ninjas);
al.add(workdone);
Collections.binarySearch(al, "Daily", null);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Exception in thread "main" java.lang.ClassCastException: class Players cannot be cast to class java.lang.Comparable (Players is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
at java.base/java.util.Collections.indexedBinarySearch(Collections.java:229)
at java.base/java.util.Collections.binarySearch(Collections.java:217)
at java.base/java.util.Collections.binarySearch(Collections.java:321)
at Main.main(Main.java:30)
compareTo() NullPointerException
When a null object calls the compareTo() function, the NullPointerException is thrown.
Program:
Java
public class CompareToExample5
{
public static void main(String[] args)
{
String s = null;
int res = s.compareTo("Coding ninjas is doing great job");
System.out.println(res);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:12)
Three Variants of compareTo() Method in Java
The compareTo() method is used in Java to compare strings or objects. There are three main variants of the compareTo() method:
1. compareTo(String anotherString)
- Compares two strings lexicographically.
- Returns:
- 0 if the strings are equal.
- A negative integer if the calling string is lexicographically less than the specified string.
- A positive integer if the calling string is lexicographically greater than the specified string.
2. compareToIgnoreCase(String anotherString)
- Compares two strings lexicographically, ignoring case differences.
- Returns values in the same way as compareTo(String).
3. compareTo(Object o)
- Used when implementing the Comparable interface for custom objects.
- Compares the current object with the specified object.
Find Length of a String Using compareTo()
The compareTo() method is not directly designed to find the length of a string, but you can use it as part of logic to deduce the length indirectly. For example, comparing substrings of varying lengths can reveal the string length.
Here’s an example:
Java
public class CompareToLengthExample {
public static void main(String[] args) {
String str = "Hello";
int length = 0;
while (true) {
if (str.substring(0, length).compareTo("") == 0) {
break;
}
length++;
}
System.out.println("Length of the string is: " + length);
}
}

You can also try this code with Online Java Compiler
Run Code
Important Examples of compareTo() in Java
Example 1: Compare Strings Lexicographically
Java
public class CompareToExample {
public static void main(String[] args) {
String str1 = "Apple";
String str2 = "Banana";
int result = str1.compareTo(str2);
if (result < 0) {
System.out.println(str1 + " is less than " + str2);
} else if (result > 0) {
System.out.println(str1 + " is greater than " + str2);
} else {
System.out.println(str1 + " is equal to " + str2);
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Apple is less than Banana
Example 2: Implementing compareTo() for Custom Objects
Java
import java.util.*;
class Student implements Comparable<Student> {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student other) {
return this.age - other.age; // Compare by age
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
public class CompareToCustomExample {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Rahul", 22));
students.add(new Student("Rohit", 20));
students.add(new Student("Virat", 25));
Collections.sort(students);
System.out.println("Students sorted by age:");
for (Student student : students) {
System.out.println(student);
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Students sorted by age: Rohit (20) Rahul (22) Virat (25)
Frequently Asked Questions
What does compareTo() do in Java?
The compareTo() method compares two strings or objects lexicographically and determines their order based on their values.
What value does compareTo() return in Java?
compareTo() returns:
- 0 if both are equal,
- A negative integer if the first is less,
- A positive integer if the first is greater.
What is compareTo() in Java 17?
In Java 17, compareTo() functions the same, comparing strings or objects lexicographically and is crucial for sorting and natural ordering.
Conclusion
In this article, we have extensively discussed the string class method compareTo() of the java programming language with various examples.
We hope this blog has helped you enhance your compareTo() method knowledge. If you would like to learn more, check out our articles on Understanding Strings, Strings Operations, and String Interview Questions In Java. Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problems, Interview experience, Coding interview questions, and the Ultimate guide path for interviews.