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.
From what I have been reading, the compareTo() method returns the difference of the Unicode numerical values of two Strings when they are compared with each other. For instance, the String "hello" when compared with the String "hello" returns an integer value of zero, since they both have exactly the same Unicode characters in them. Based on my understanding of this method, "hello" should return zero when compared to "olleh", because the two Strings have the exact same Unicode characters in them. Instead, though, I am getting integer value of 7 returned to the console. Can someone break this down a bit for me to help me understand it better? Thanks in advance. Here is my code:
String str1 = "hello";String str2 = "olleh";System.out.println(str1.compareTo(str2)); // 7
Videos
What is the purpose of the compareTo method in Java?
Which classes in Java implement the compareTo method?
How does the compareTo method differ from the equals method in Java?
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.
compareTo for Strings returns -1 if the first String (the one for which the method is called) comes before the second String (the method's argument) in lexicographical order. "ab2" comes before "ab3" (since the first two characters are equal and 2 comes before 3) and also before "ac3" (since the first character is equal and b comes before c), so both comparisons return -1.