aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Compare()  - from Master Exam Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Compare()  - from Master Exam" Watch "Compare()  - from Master Exam" New topic
Author

Compare() - from Master Exam

Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661
This is from MasterExam

I am not sure what is going on in the Compare Method.
How is it doing the comparision.




The answer is good


The future belongs to those who believe in the beauty of their dreams.Dream BIG!
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
public int compare(String s1,String s2)
{
return s2.charAt(1)-s1.charAt(1);
}

In the code above, say s1="cat", and s2="dog".
The s2.charAt(1) = 'a' and s1.charAt(1)='o'.
Therefore compare() will return the int value of 'o'-'a'.

Note that compare() does not account for when s1 or s2 or both have length 1 or 0. It should have code to take care of these situations and also when either or both of them are null.
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
I meant to say s1.charAt(1) = 'a' and s2.charAt(1) ='o'
Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661
So that means its comparing the three words in (reverse of )Alphabetical order based on the second letter as its
s2.charAt(1) -s1.charAt(1)
and not
s1.charAt(1) -s2.charAt(1).

Right?
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
Right
Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661
THanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Compare() - from Master Exam