• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

strings doubt

 
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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??
 
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks

does compareTo applies only for char or for everything
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic