• 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

String and String Buffer

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i have run the following code
class MWC200
{
public static void main (String[] args)
{
String s1 = "ABC";
StringBuffer s2 = new StringBuffer(s1);
System.out.print(s2.equals(s1) + "," + s1.equals(s2));
}
}
output is false,false

but i think it should be run time error..as string and string buffer objs cannot be compared....it should give class cast exception....if we want to compare both of them..first the string buffer should be converted to string using toString() method..and then we can compare them....and also string buffer class does not override equals method of the object class....then why this code is executing correctly....without exception.
 
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you might be confusing equals() contract with the compareTo() contract.

compareTo throws an ClasCastException when the objects compared are completely unrelated, but equals never throws an exeption. It simply return false as in this case.

The equals method is implemented in such a way it does not throw a ClassCastException



While the compareTo method is implemented to do casting, and if the casting fails it will throw a ClassCastException:

[code]
public int compareTo(Object paramObject){
MyClass obj = (MyClass) paramObject
}
[code]

Regards,
Edwin Dalorzo.
[ January 12, 2006: Message edited by: Edwin Dalorzo ]
 
vandu matcha
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thank u edwin...actually after posting my doubt ..i tried with compareTo method...it gave class cast exception..u are obsolutely correct.....
 
reply
    Bookmark Topic Watch Topic
  • New Topic