Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compareTo() function in Java

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"?

like image 981
Vamsi Mohan Avatar asked Nov 29 '25 16:11

Vamsi Mohan


1 Answers

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.

like image 68
Eran Avatar answered Dec 02 '25 05:12

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!