What is java String compareTo method and What is Java lexicographically

226 Views Asked by At

I don't know what the output means? Will anyone help me with this? Please explain me how it works.

  public class LastIndexOfExample{  
  public static void main(String args[]){  
   String s1="hello";  
   String s2="hello";  
   String s3="meklo";  
   String s4="hemlo";  
   System.out.println(s1.compareTo(s2));  
   System.out.println(s1.compareTo(s3));  
   System.out.println(s1.compareTo(s4));  
  }
}  

Then the output is: 0 -5 -1

1

There are 1 best solutions below

10
On BEST ANSWER

From compareTo javadoc:

If there is an index at which the two strings differ, the result is the difference between the two char's at the lowest such index

Full Javadoc:

    /**
     * Compares this string to the given string.
     *
     * <p>The strings are compared one {@code char} at a time.
     * In the discussion of the return value below, note that {@code char} does not
     * mean code point, though this should only be visible for surrogate pairs.
     *
     * <p>If there is an index at which the two strings differ, the result is
     * the difference between the two {@code char}s at the lowest such index.
     * If not, but the lengths of the strings differ, the result is the difference
     * between the two strings' lengths.
     * If the strings are the same length and every {@code char} is the same, the result is 0.
     *
     * @throws NullPointerException
     *             if {@code string} is {@code null}.
     */
    public native int compareTo(String string);

And from the online documentation (link above):

The result is a negative integer if this String object lexicographically precedes the argument string