compareTo() function in Java

Vamsi Mohan :

I have written the code below

import java.util.*;
class compare{
    public static void main(String []args){
        String s1="java";
        String s2="javaProgramming";
        System.out.println(s1.compareTo(s2));
    }
}

The output for this code is -11. Since there is no character for termination of string in java, which character in "java" is being compared with 'P' in "javaProgramming"?

Eran :

The 'P' character is not compared to anything in the first String.

It only compares the first 4 characters of the 2 Strings, which are equal to each other.

Then it returns the length of the first String minus the length of the second 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;
        }
        k++;
    }
    return len1 - len2;
}

Since the second String is longer, and the first String is contained in the second, returning any negative value will do, since the shorter String should come first in lexicographical order.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11285&siteId=1