Search code examples
javastringcompareto

Manually calculate output from string compareTo string


I'm trying to see how to manually calculate the output when comparing strings as questions like it have come up in past papers I'm practicing.

I understand that the result is negative if the string lexicographically (according to unicode) precedes the argument string, positive if it follows it and zero if they are equal. I don't see how to calculate the value (beyond the sign).

I have the code which gives the output 1, -1, -3, 3. I see why each is positive or negative but not why it is 1 or 3.

public class CompareToPractice {
    public static void main(String[] args) {
        String str1 = "bode";
        String str2 = "bod";
        String str3 = "bodge";
        String str4 = "bog";

        int result1 = str1.compareTo(str2);
        System.out.println(result1);
        int result2 = str2.compareTo(str1);
        System.out.println(result2);
        int result3 = str3.compareTo(str4);
        System.out.println(result3);
        int result4 = str4.compareTo(str3);
        System.out.println(result4);
    }
}

Thank you


Solution

  • Its the difference between the characters 'd' and 'e' (ascii difference).

    This is the code of compareTo

    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;
           }
           k++;
        }
        return len1 - len2;
    }
    

    As you can see from line if (c1 != c2). If 2 characters are not equal, then the result will be the subtraction of those 2 values.

    In your case str3.compareTo(str4) was "bodge" - "bog".
    So 'd'-'g' (ASCII value: 100 - 103 = -3)