This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

strings doubt

 
Karu Raj
Ranch Hand
Posts: 481
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 340
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Karu Raj
Ranch Hand
Posts: 481
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks

does compareTo applies only for char or for everything
 
Thomas Drew
Ranch Hand
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic