Thursday, July 4, 2024
HomeLanguagesJavaJava String compareTo() Method with Examples

Java String compareTo() Method with Examples

Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well. 

The String class of Java comprises a lot of methods to execute various operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), substring(), etc. Out of these methods, we will be focusing on the Java String compareTo() method in this article.

Java String.compareTo() Method

The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a positive number, a negative number, or 0. It compares strings on the basis of the Unicode value of each character in the strings.

  • If the first string is lexicographically greater than the second string, it returns a positive number (difference of character value).
  • If the first string is less than the second string lexicographically, it returns a negative number, and,
  • If the first string is lexicographically equal to the second string, it returns 0.

Note:

  • if string1 > string2, it returns positive number
  • if string1 < string2, it returns negative number
  • if string1 == string2, it returns 0

There are three variants of the compareTo() method which are as follows:

  1. using int compareTo(Object obj)
  2. using int compareTo(String anotherString)
  3. using int compareToIgnoreCase(String str)  

1. int compareTo(Object obj)

This method compares this String to another Object.

Syntax: 

int compareTo(Object obj)

Parameters: 

obj: the Object to be compared.

Return Value:The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

Below is the implementation of the above method:

Java




// Java code to demonstrate the
// working of compareTo()
public class Cmp1 {
    public static void main(String args[])
    {
 
        // Initializing Strings
        String str1 = "neveropen";
        String str2 = new String("neveropen");
        String str3 = new String("astha");
 
        // Checking if neveropen string
        // equates to neveropen object
        System.out.print(
            "Difference of neveropen(obj) and neveropen(str) : ");
        System.out.println(str1.compareTo(str2));
 
        // Checking if neveropen string
        // equates to astha object
        System.out.print(
            "Difference of astha(obj) and neveropen(str) : ");
        System.out.println(str1.compareTo(str3));
    }
}


Output

Difference of neveropen(obj) and neveropen(str) : 0
Difference of astha(obj) and neveropen(str) : 6

2. int compareTo(String anotherString) 

This method compares two strings lexicographically. 

Syntax: 

int compareTo(String anotherString)

Parameters: 

anotherString:  the String to be compared.

Return Value: The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

Below is the implementation of the above method:

Java




// Java code to demonstrate the
// working of compareTo()
 
public class Cmp2 {
    public static void main(String args[])
    {
 
        // Initializing Strings
        String str1 = "neveropen";
        String str2 = "neveropen";
        String str3 = "astha";
 
        // Checking if neveropen string
        // equates to neveropen string
        System.out.print(
            "Difference of neveropen(str) and neveropen(str) : ");
        System.out.println(str1.compareTo(str2));
 
        // Checking if neveropen string
        // equates to astha string
        System.out.print(
            "Difference of astha(str) and neveropen(str) : ");
        System.out.println(str1.compareTo(str3));
    }
}


Output

Difference of neveropen(str) and neveropen(str) : 0
Difference of astha(str) and neveropen(str) : 6

3. int compareToIgnoreCase(String str)  

This method compares two strings lexicographically, ignoring case differences. 

Syntax:

int compareToIgnoreCase(String str)

Parameters: 

str: the String to be compared.

Return Value: This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.

Below is the implementation of the above method:

Java




// Java code to demonstrate the
// working of compareToIgnoreCase()
 
public class Cmp3 {
    public static void main(String args[])
    {
 
        // Initializing Strings
        String str1 = "geeks";
        String str2 = "gEEkS";
 
        // Checking if neveropen string
        // equates to neveropen string
        // case sensitive
        System.out.print(
            "Difference of geeks and gEEkS (case sensitive) : ");
        System.out.println(str1.compareTo(str2));
 
        // Checking if neveropen string
        // equates to astha string
        // case insensitive
        // using compareToIgnoreCase()
        System.out.print(
            "Difference of geeks and gEEkS (case insensitive) : ");
        System.out.println(str1.compareToIgnoreCase(str2));
    }
}


Output

Difference of geeks and gEEkS (case sensitive) : 32
Difference of geeks and gEEkS (case insensitive) : 0

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments