How does compareTo work?

Harsh picture Harsh · Sep 7, 2015 · Viewed 20.1k times · Source

I know that compareTo returns a negative or positive result on how well one string correlates to the other, but then why:

public class Test {
    public static void main(String[] args) {
        String y = "ab2";
        if(y.compareTo("ac3") == -1) {
            System.out.println("Test");
        }
    }
}

is true and

public class Test {
    public static void main(String[] args) {
        String y = "ab2";
        if(y.compareTo("ab3") == -1) {
            System.out.println("Test");
        }
    }
}

is also true?

Answer

Tunaki picture Tunaki · Sep 7, 2015

The general contract of Comparable.compareTo(o) is to return

  • a positive integer if this is greater than the other object.
  • a negative integer if this is lower than the other object.
  • 0 if this is equals to the other object.

In your example "ab2".compareTo("ac3") == -1 and "ab2".compareTo("ab3") == -1 only means that "ab2" is lower than both "ac3" and "ab3". You cannot conclude anything regarding "ac3" and "ab3" with only these examples.

This result is expected since b comes before c in the alphabet (so "ab2" < "ac3") and 2 comes before 3 (so "ab2" < "ab3"): Java sorts Strings lexicographically.