The compareTo() and compareToIgnoreCase() methods allow you to compare strings, but they allow you to calculate how much one string is larger than another. As I understand.

  String a = "A"; String b = "z"; System.out.println(a.compareToIgnoreCase(b)); System.out.println(a.compareTo(b)); 

Here is what brought:

// - 25
// - 57

I do not understand in detail how this methods work, who can tell?

  • one
    Can tell the documentation . - Enikeyschik
  • “how much one line is bigger than the other” is a completely meaningless thing. Strings are not numbers, you cannot say that "this line is twenty-five lines longer." Above the lines, the order relation is defined, but there is no concept of "line difference" - m. vokhm

2 answers 2

Each character string is converted to unicode. If the strings are equal, 0 is returned, if the string you are comparing with another is lexicographically larger, then a positive number is returned; if less, a negative number is returned.

  • lexicographically more how to understand? - user316928
  • Lexicographic comparison is the comparison of letters and letter numbers in the alphabet. The letter A is the first in the alphabet, the letter Z is the last, respectively, and their “weight” is different. The comparison is such that if the first letters of the line are equal, then the second letters are compared. It is like in dictionaries or phone books, the strings "abc" and "zxc" are equal in length, so they will be compared on the position of characters in the alphabet. - Constantin Naumov
  • @PetrIvanov alphabetically, to put it simply. Only with special characters and so on, in accordance with the order of characters in Unicode - m. vokhm Nov.

The essence of any comparator is to return the integer result of the comparison of objects. By holding down the Ctrl key and clicking on the method in most IDEs, you can proceed to the implementation of the method that interests us. This is how the string comparator works:
(strings are already cast to byte[] arrays)

 @HotSpotIntrinsicCandidate public static int compareTo(byte[] value, byte[] other) { int len1 = value.length; int len2 = other.length; int lim = Math.min(len1, len2); for (int k = 0; k < lim; k++) { if (value[k] != other[k]) { return getChar(value, k) - getChar(other, k); } } return len1 - len2; } 

He element-wise compares the characters from the first to the end of the shortest line. If there is a pair of different characters, then the result of comparing the first such pair is returned. If all characters match, then the result of comparing string lengths is returned.