compareTo on strings

Just don’t quite get what it means, the difference between strings. Characters, fine, but how do you compute string values? I thought it might be the diff of the sums of characters, but that doesnt seem to be the case with a couple of trials…

Type your question above this line.


Hi @Yo_Sato
It works on Unicode values of characters and computes difference character-wise in string values. It keeps on computing the difference character by character and returns zero if all the characters are same. If this method finds any comparison different, it computes its Unicode value’s difference and returns the difference.

For Example,

  • if there are two strings “Hello” and “Hello”, Result will be 0 because the difference between all characters is zero.

  • If there are two strings “Hello” and “HELLO”, the result would be 32. Why? The reason is; Two comparisons are performed here. First, “H” and “H”, their difference is zero so it moves to the next character in both strings i.e. “e” and “E”. Now, Unicode of “e” and “E” are 101 and 69 respectively. So the difference is 101-69 = 32. This method returns 32 without checking the remaining characters.

  • If there are two strings “HELLO” and “Hello”, the result would be -32. Because “E” and “e” give the output as 69-101 = -32.

I hope you understand this method’s working now.

Thank you :slight_smile:

1 Like