Atharva Pandey Atharva Pandey - 1 year ago 72
Java Question

How is lexicographical Comparison done mathamatically?

I understand that compareTo when comparing Strings in java does lexicographical comparison. I tried searching for how it calculates the value internally.I want to know how we get the value mathamatically with some example.

Answer Source

String.compareTo() is not 'lexicographical' or something. It is alphabetical. Let's look inside the source code of class java.lang.String:

public int compareTo(String anotherString) {
    int len1 = value.length;
    int len2 = anotherString.value.length;
    int lim = Math.min(len1, len2);
    char v1[] = value;
    char v2[] = anotherString.value;

    int k = 0;
    while (k < lim) {
        char c1 = v1[k];
        char c2 = v2[k];
        if (c1 != c2) {
            return c1 - c2;
    return len1 - len2;

As you can see, it just compares character to character, and returns difference between first pair of non-equal characters (character type in Java is numeric type which just have special print behavoir) if one string is not a substring of another. If it does, CompareTo returns difference between lengthes of strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download