aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes strings doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "strings doubt" Watch "strings doubt" New topic
Author

strings doubt

Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 479
String s5 = "AMIT";
String s6 = "amit";
System.out.println(s5.compareTo(s6));
System.out.println(s6.compareTo(s5));
System.out.println(s6.compareTo(s6));

the output i got is -32,32,0.

please explain me what is teh compareTo method actually does??
Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
Hi,
when you compare s5 to s6, it checks if s5 is smaller than equal to or greater than s6. and it returns an integer value according to the result.

here as it compares s5 to s6 it finds that s5 contains "AMIT" and s6 contains "amit". so it starts comparing both string character by character

as there is a differenct of -32 (A-a==> 65-97==>-32 (unicode values)) it prints -32

similarly it does the same thing for s6.compareTo(s5).

but when you compare s6 to s6 itself, it finds no differnence. that is the strings are equal. hence prints 0;

Hope it helps
Correct if am wrong

Sandy


Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 479
thanks

does compareTo applies only for char or for everything
Thomas Drew
Ranch Hand

Joined: Sep 15, 2004
Posts: 47
This Link might help. If you look at the bottom of the page their is a list of Objects which use the Comparable interface.
http://alt.textdrive.com/assets/public/docs/java.lang.Comparable.cls.html
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: strings doubt