This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
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 Building Microservices this week in the Design 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: 481
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: 481
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
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: strings doubt
 
It's not a secret anymore!