Reputation: 3
I am new here so I don't know much whether there are any sections for different questions and the like. So sorry for that in advance.
So, my question is, can anyone tell me the hierarchy of characters or rather strings in compareTo() function of java. In this code...
String s1 = "HELLO";
String s2 = "hello";
int c;
c = s1.compareTo(s2);
System.out.println(c);
In here, the output is -32, which means 'H' is smaller than 'h'. So I would like to know the list in which the characters are arranged from highest to the lowest value. Thanks in advance.
Upvotes: 0
Views: 366
Reputation: 901
compareTo method works as follow:-
Syntax :
int compareTo(String anotherString)
Parameters :
anotherString : the String to be compared.
Return Value :
The value 0 if the argument is a string lexicographically equal to this string;
a value less than 0 if the argument is a string lexicographically greater than this string;
and a value greater than 0 if the argument is a string lexicographically less than this string.
In your case, you are trying to compare
String s1 = "HELLO"; // ASCII value for H is 72
String s2 = "hello"; // ASCII value for h is 104
It will compare character by character and compare till the character they are different and then return the subtraction of both ASCII value else return 0.
In your case value of H and h different, it returns the subtraction of ASCII(H)-ASCII(h)=-32.
You can refer the different ASCII value of character at https://theasciicode.com.ar/ascii-printable-characters/capital-letter-z-uppercase-ascii-code-90.html
Upvotes: 1
Reputation: 1627
The compareTo() method uses Unicode values to compare the strings. A full list can be found here: https://en.wikipedia.org/wiki/List_of_Unicode_characters
It could be useful to look up Unicode values on google images for a chart.
Upvotes: 0