Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

String compareTo

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

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()

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.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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:

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);
   }
}

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:

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));  
    }
}

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:

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));  
    }  
}

Output:

-32

compareTo() ClassCastException

When objects of incompatible types are compared, the ClassCastException is produced.

Program:

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);  
    }      
}

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:

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);  
    }  
}

Output:

Exception in thread "main" java.lang.NullPointerException
    at Main.main(Main.java:12)

Frequently Asked Questions

Name the exceptions thrown by compareTo() method.

compareTo() method throws two exceptions: ClassCastException and NullPointerException.

When objects of incompatible types are compared, the ClassCastException is produced and when a null object calls the compareTo() function, the NullPointerException is thrown.

 

What is the return type of compareTo ()?

The compareTo() method is used to compare two objects. The compareTo() function of the Java String class compares the given string to the current string lexicographically. It returns a positive, negative, or zero value.

 

How do you use compareTo to compare two int values?

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.

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.

Do upvote our blog to help other ninjas grow. Happy Coding!

Topics covered
1.
Introduction
2.
String compareTo()
3.
Example 
4.
compareTo() Method
5.
compareTo() with Empty String
6.
compareTo() case sensitive 
7.
compareTo() ClassCastException
8.
compareTo() NullPointerException
9.
Frequently Asked Questions
9.1.
Name the exceptions thrown by compareTo() method.
9.2.
What is the return type of compareTo ()?
9.3.
How do you use compareTo to compare two int values?
10.
Conclusion