Java String compareTo() Method

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Strings are a fundamental data type in Java and are widely used in applications for storing and manipulating text. Strings in Java are objects backed by character arrays, making them immutable. Once a string is created, its contents cannot be changed. To “modify” a string, a new string object must be created.

Java provides a rich set of methods for manipulating strings. These methods allow you to compare strings, search for substrings, and concatenate strings.

In this article, we will focus on the compareTo() method of the Java String class, which allows you to perform lexicographical comparison of strings.

Java String compareTo() Method

The compareTo() method of the Java String class allows you to compare two strings lexicographically, meaning in dictionary order. It returns an integer indicating whether the reference string (the string on which the method is called) is more significant than, equal to, or less than the string argument passed to the process.

Specifically, it returns:

  • A positive number if the reference string is greater than the argument string
  • 0 if the strings are equal
  • A negative number if the reference string is less than the argument string

The comparison is based on the Unicode value of each character in the strings. The method compares the strings character by character, comparing the Unicode values. The first character that doesn’t match determines the result of the comparison.

For example, “abc” is more significant than “abb” because the Unicode value of ‘c’ is greater than that of ‘b’. “apple” is greater than “apply” because although the first four characters are equal, ‘p’ is greater than ‘l’.

Variants of Java compareTo() Method

The String class has three variants of the compareTo() method:

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

int compareTo(Object obj)

This version of compareTo() expects an Object as a parameter and compares the reference string to the object’s string representation.

Syntax:

public int compareTo(Object obj)

Example:

public class CompareStrings {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";
        String s3 = "world";

        int result1 = s1.compareTo(s2); // 0 (s1 equals s2)
        int result2 = s1.compareTo(s3); // -ve (s1 < s3)

        System.out.println("Comparison between s1 and s2: " + result1);
        System.out.println("Comparison between s1 and s3: " + result2);
    }
}

Output:
Comparison between s1 and s2: 0
Comparison between s1 and s3: -15

Here, s1.compareTo(s2) compares the string “hello” with string “hello” and returns 0 as both are equal.

s1.compareTo(s3) compares “hello” with “world” and returns a negative number as “hello” comes before “world” in dictionary order.

int compareTo(String anotherString)

This version expects a String object as a parameter and compares the reference string to the string passed as a parameter.

Syntax:

public int compareTo(String anotherString)

Example:

public class CompareStrings {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";
        String s3 = "world";

        int result1 = s1.compareTo(s2); // 0 (s1 equals s2)
        int result2 = s1.compareTo(s3); // -ve (s1 < s3)

        System.out.println("Comparison between s1 and s2: " + result1);
        System.out.println("Comparison between s1 and s3: " + result2);
    }
}

Output:
Comparison between s1 and s2: 0
Comparison between s1 and s3: -15

The behavior is similar to the compareTo(Object) variant. s1.compareTo(s2) compares “hello” and “hello” and returns 0. s1.compareTo(s3) compares “hello” and “world”, finding “hello” is lesser and returns a negative value.

int compareToIgnoreCase(String str)

This version compares two strings, ignoring case differences.

Syntax:

public int compareToIgnoreCase(String str)

Example:

public class CompareStrings {
    public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = "hello";

        int result1 = s1.compareTo(s2); // -ve (s1 < s2)
        int result2 = s1.compareToIgnoreCase(s2); // 0 (equals with ignore case)

        System.out.println("Comparison between s1 and s2: " + result1);
        System.out.println("Comparison between s1 and s2 (ignore case): " + result2);
    }
}

Output:
Comparison between s1 and s2: -32
Comparison between s1 and s2 (ignore case): 0

Here, s1.compareTo(s2) considers case and finds “Hello” is lesser than “hello”.

But s1.compareToIgnoreCase(s2) ignores case and finds them equal, returning 0.

Conclusion

The Java String compareTo() method is an essential string manipulation tool for lexical comparison of strings. By comparing strings character-by-character based on Unicode value, it returns an integer indicating whether a string is greater than, equal to, or less than another string. The method has variants to compare strings while ignoring case differences.

Mastering compareTo() is key for efficient string sorting, searching, and other text processing tasks in Java programming. With its simplicity and power, compareTo() is a valuable addition to any Java developer’s toolkit.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses
Image

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

Your email address will not be published. Required fields are marked *