Search code examples
javacompareto

Why does System.out.println("0:00".compareTo("0")); result in 3?


I am really curious.

Why does System.out.println("0:00".compareTo("0")); result in 3? I was expecting 10 as the ASCII code for : 58 and the ASCII code for 0 is 48.


Solution

  • Please read the documentation to String.compareTo:

    https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)

    If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:

    this.charAt(k)-anotherString.charAt(k)
    

    If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:

    this.length()-anotherString.length()
    

    First charater of the first string is equal to the whole second string ("0"). Therefore they are compared by their lengths. The first string is 4 characters long, and the second is 1. Therefore difference is 3