| Author |
String and String Buffer
|
vandu matcha
Ranch Hand
Joined: Dec 28, 2005
Posts: 57
|
|
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.
|
 |
Edwin Dalorzo
Ranch Hand
Joined: Dec 31, 2004
Posts: 961
|
|
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
Joined: Dec 28, 2005
Posts: 57
|
|
|
thank u edwin...actually after posting my doubt ..i tried with compareTo method...it gave class cast exception..u are obsolutely correct.....
|
 |
 |
|
|
subject: String and String Buffer
|
|
|