Indy,
Take a deep breath and read on..
regds
maha anna
Char chart (lexographically ordered) ...1 2 3 4 5 6 7 8 9 10 .....A B C D ...a b c d......
- char 'A' lexographically precedes char 'a'
- char 'B' lexographically precedes char 'b'
- char '1' lexographically precedes char '2'
- char '2' lexographically precedes char '3'
- In otherwords any char (c1) whose UNICODE VALUE is lesser than
another char (c2), then c1 is said to be lexographically
preceeding char c2.
- Here in our example char 'A' unicode value = 65
char 'a' unicode value is 97. So this means in our
lexographically ordering chart 'A' comes first and then
'a' comes later.
Unicode value chart
-------------------
1=49
2=50
3=51
4=52
5=53
6=54
7=55
8=56
A=65
B=66
C=67
D=68
a=97
b=98
c=99
d=100
Having said that, what str1.compareTo(String str2) does is,
this method just takes these 2 strings. Let us assume String s1 is in our left hand and String s2 is in our right hand. What you do is , just compare each char from index 0 to
the last char from str1 with the correxponding char at str2.
For example
String s1 = a b c d ( 97 98 99 100 )
String s2 = A B C D ( 65 66 67 68)
Compare
'A' with 'a' 'B' with 'b' 'C' with 'c' 'D' with 'd'
While doing so, if you encounter a char from str1 whose value is NOT SAME as that of , the corresponding char of str2, this means,
you found a char in str1 which is lexographically GREATER
than that corr. char of Str2.
In our example, the check breaks out in the first char itself.
because char 'a' is GREATER than char 'A' (s1.charAt(0) > s2.charAt(0) )
In other words 97 is GREATER than 65.
So what s1.compareTo(s2) does is it just finds out the very first differing char from str1 and returns the differnece. In our case it is 97-65 = 32. Also note that this value may be -ve also. When will you get -ve value? When the compared char from str1 is less than the corr. compared char of str2
For example the reverse of the above example
String s1 = A B C D ( 65 66 67 68)
String s2 = a b c d ( 97 98 99 100 )
Here also the check comes out in the first char check itself.
'A' is NOT SAME as 'a'
so calculate the difference
65 - 97 = -32 If all goes well, which means BOTH strings are SAME in contents, (i.e) s1.equals(s2) is true, then the checks are all through from starting to end and there is NO DIFFERENCE in unicode value so 0(zero) is returned.
Also note that if the first string str1's length is LESS than str2's length , then there is no point in checking char by
char basis, so the difference in length is returned.
str1 = "AB"
str2 = "ABCD"
so s1.compareTo(s2) = 2 - 4 = -2;
Simillarly
str1 = "ABCD"
str2 = "AB"
so s1.compareTo(s2) = 4 - 2 = 2;
************
THE END
**************
[This message has been edited by maha anna (edited April 30, 2000).]