java – What is the working principle of the compareTo() method?


Who can explain the principle of comparison when there are different variants of the compared strings, which can differ both in letters and in length?


Strings in Java (and in many places in general) are compared using the Lexicographic Order . You can also read about what it is here . General meaning, alphabetically.

If we talk specifically about the String class, then it implements the Comparable interface. The documentation describes in detail what the compareTo() method should return. In short, it determines the order of the elements.

o1.compateTo(o2) :

> 0 – if o1 should come after o2 (in case of numbers o1>o2 , with strings, alphabetically o2 comes before o1)

=0 – if o1 and o2 are equivalent (not necessarily equal! BUT, if o1.equals(o2) == true , then it is desirable that o1.compareTo(o2) == 0 , otherwise consistency is lost)

<0 – if o1 should come before o2 (in case of numbers o1<o2 , with strings, alphabetically o1 comes before o2)

Scroll to Top