Table of contents
1.
Introduction
2.
String compareTo()
3.
Example 
3.1.
compareTo() Method
3.2.
Java
3.3.
compareTo() with Empty String
3.4.
Java
3.5.
compareTo() case sensitive 
3.6.
Java
3.7.
compareTo() ClassCastException
3.8.
Java
3.9.
compareTo() NullPointerException
3.10.
Java
4.
Three Variants of compareTo() Method in Java
5.
Find Length of a String Using compareTo()
5.1.
Java
6.
Important Examples of compareTo() in Java
6.1.
Example 1: Compare Strings Lexicographically
6.2.
Java
6.3.
Example 2: Implementing compareTo() for Custom Objects
6.4.
Java
7.
Frequently Asked Questions
7.1.
What does compareTo() do in Java?
7.2.
What value does compareTo() return in Java?
7.3.
What is compareTo() in Java 17?
8.
Conclusion
Last Updated: Nov 22, 2024
Easy

String compareTo

Author Aditi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The compareTo() function lexicographically compares two strings (in the dictionary order). With the assistance of examples, we will learn about the Java String compareTo() function in this article. But because it is a method in Java, you must have prerequisites for programming in the Java language.

Let's dive into the article to get more information about the string compareTo() method.

String compareTo

String compareTo()

compareTo() method does the comparison based on each character's Unicode value in the strings. 

Syntax

public int compareTo(String str)
public int compareTo(Object obj)

The function returns 0 if the string is equal to the other string. A number less than 0 is returned if the string is shorter (fewer characters), whereas a value greater than 0 is returned if the string is longer (more characters).

The following two exceptions are thrown:

  • If this object cannot be compared to the supplied object, a ClassCastException will be thrown.
  • If the provided object is null, a NullPointerException is thrown.

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

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

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

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

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

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

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

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

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 StringsStrings 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 problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Live masterclass