How does compareTo works while comparing the String?? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 1

How does compareTo works while comparing the String??

"DEDICATE".compareTo("DEVOTE") gives -18 as output why? Kindly explain the calculation.

2nd Mar 2021, 4:12 PM
Aman sharma
4 Respostas
+ 3
and In words, DE matches but after D,V not matches result negetive value as difference from its asci value 'D' - 'V' = -18
2nd Mar 2021, 4:33 PM
Jayakrishna šŸ‡®šŸ‡³
+ 1
Aman sharma compareTo() Ā is used for comparing two strings . Each character of both strings are converted into a Unicode value. However, if both the strings are equal, then this method returns 0 else it only result either negative or positive value.
2nd Mar 2021, 4:22 PM
ā¤ā˜†Naniā˜†ā¤
ā¤ā˜†Naniā˜†ā¤ - avatar
+ 1
Aman sharma also it's the integer method so it's return only integer type values
2nd Mar 2021, 4:23 PM
ā¤ā˜†Naniā˜†ā¤
ā¤ā˜†Naniā˜†ā¤ - avatar
0
internally it calls this public static int compareTo(byte[] value, byte[] other, int len1, int len2) { 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; } // java 15
2nd Mar 2021, 8:44 PM
zemiak