here you are comparing in reverse order. String class charAt() method will find the character value in specified location.remember charater is also integer value only, so you can do like int i= 'a'-'a';

SCJP 1.5 94%.
The greatest glory in living lies not in never falling, but in rising every time we fall.

VidyaVikas Yalamanchili

Greenhorn

Posts: 10

posted 8 years ago

HI

In the above code compare should always return a int.When you operate on characters every character can convert to an int.

you can give int i='a'

which will get i value 97.it is the ascii for a.So when you do s.charAt[1]-s.charAt[1] the sort happens on the second character of the string.

with Regards,<br />VidyaVikas Yalamanchili SCJP 5.0

sweety sinha

Ranch Hand

Posts: 76

posted 8 years ago

i get a little bit. so is it doing like this:- s2.charAt(1)="Ugly" - s1.charAt(1)="Bad"

please explain

Pranav Bhatt

Ranch Hand

Posts: 284

posted 8 years ago

by Sweety so is it doing like this:- s2.charAt(1)="Ugly" - s1.charAt(1)="Bad"

Try adding the bold line below you will get to know.

The output of this is as-:

g a o a o g

[ September 15, 2008: Message edited by: Pranav Bhatt ]

arulk pillai

Author
Ranch Hand

Posts: 3393

posted 8 years ago

Basically it is doing a revers sort based on the second character of each word. charAt is 0 based. so 1 means second character and 0 means first character.

The comparator method returns 0 if 2 objects are equal and a -ve value if s1 < s2 and +ve value if s1 > s2. For example if you have Bad as s1 & Ugly as s2