please explain why the output in this code as follows. I really don't understand. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

please explain why the output in this code as follows. I really don't understand.

String str1 = "JAVA"; String str2 = " java "; int n = str1.compareTo(str2); System.out.println(n) ; // -32

8th Jul 2019, 8:58 AM
turing-314
turing-314 - avatar
4 Answers
+ 6
compareTo() returns difference of character values... Ascii J = 74 Ascii j = 106 74 - 106 = -32
8th Jul 2019, 9:17 AM
unChabon
unChabon - avatar
+ 3
diego Code, thanks very much!
8th Jul 2019, 9:18 AM
turing-314
turing-314 - avatar
+ 2
You're welcome! :)
8th Jul 2019, 9:19 AM
unChabon
unChabon - avatar
+ 2
If you would sort theese two Strings, the negative value means that JAVA comes before java: JAVA, java As a rule: if you compare two Strings or other objects: value < 0 -> object1 < object2 value = 0 -> objects are equal value > 0 -> object1 > object2 https://code.sololearn.com/crCKDq5I22V8/?ref=app
8th Jul 2019, 1:55 PM
Denise Roßberg
Denise Roßberg - avatar