Java String compareTo() method – Codekru

In this post, we will learn about the compareTo() method of the String class.

  • Method declaration – public int compareTo(String anotherString).
  • What does it do? It will compare two strings in a lexicographical manner ( means in the alphabetical order), and the comparison is based on the Unicode value of each character.
  • What does it return? It returns an int value after comparing the two strings.

If we write s1.compareTo(s2), then there are only three possibilities –

If s1 = s2 , it will return 0
if s1 > s2 , it will return positive number
if s1 < s2, then it will return negative number

Code example

public class Codekru {

	public static void main(String[] args) {
		String s1 = "cde";
		String s2 = "cde";
		String s3 = "abc";
		String s4 = "fgh";

		System.out.println("s1 compareTo with s2 = " + s1.compareTo(s2));
		System.out.println("s1 compareTo with s3 = " + s1.compareTo(s3));
		System.out.println("s1 compareTo with s4 = " + s1.compareTo(s4));
	}
}

Output –

s1 compareTo with s2 = 0
s1 compareTo with s3 = 2
s1 compareTo with s4 = -3
Time complexity of the compareTo() method
  • Best-case time complexity – The best-case scenario is when the first character of the strings doesn’t match or one of the string lengths is 0. So, the best-case time complexity would be O(1).
  • Worst-case time complexity – Worst-case scenario is when both strings are identical, or the last character of the smaller string doesn’t match. Then the worst-case time complexity would be O(n), where n is the length of the smaller string.

So, the average time complexity of the compareTo() method would be O(n), where n is the length of the smaller string.

The What If scenarios

What if we try to use the compareTo function with an empty String?

The easiest way of knowing this is by doing it 😛

public class Codekru {

	public static void main(String[] args) {

		String s1 = "hello codekru";
		String s2 = "abc";
		String s3 = "";

		System.out.println("s1 compareTo with s3 = " + s1.compareTo(s3));
		System.out.println("s3 compareTo with s1 = " + s3.compareTo(s1));
		System.out.println("s2 compareTo with s3 = " + s2.compareTo(s3));

	}
}

Output –

s1 compareTo with s3 = 13
s3 compareTo with s1 = -13
s2 compareTo with s3 = 3

Did you notice some patterns? If you want more insight, below is the internal implementation of the compareTo() function logic. In the case of an empty string, it just returns the difference between the first and the second string lengths.

    private static int compareToUTF16Values(byte[] value, byte[] other, int len1, int len2) {
        int lim = Math.min(len1, len2);
        for (int k = 0; k < lim; k++) {
            char c1 = getChar(value, k);
            char c2 = StringUTF16.getChar(other, k);
            if (c1 != c2) {
                return c1 - c2;
            }
        }
        return len1 - len2;
    }

If one of the lengths is 0, then “Iim” would be 0, and in that scenario, the function would return len1 – len2.

What if we try to use the compareTo function with a null String?

In this case, it will throw a NullPointerException

public class Codekru {

	public static void main(String[] args) {

		String s1 = "hello codekru";
		String s2 = null;

		System.out.println("s1 compareTo with s3 = " + s1.compareTo(s2));

	}
}

Output –

Exception in thread "main" java.lang.NullPointerException: Cannot read field "value" because "anotherString" is null
	at java.base/java.lang.String.compareTo(String.java:1215)

If you want to learn more about Strings and its methods, we recommend you read this article.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected]

Liked the article? Share this on