+ 3

Operation of compareTo() function in java

Can we compare StringBuffer and String objects in java using compareTo() method ? If not then why? Can we compare them using equals() and "=="?

14th Aug 2020, 9:09 AM
Gauri Shirkande
Gauri Shirkande - avatar
4 Answers
+ 11
Gauri Shirkande You can't compare String and Stringbuffer object, although each class has compareTo() method(stringbuffer class has compareTo() method since java 11) but both takes different parameter. You have to convert Stringbuffer to string and them use compareTo() method. https://javagoal.com/comparable-java/
14th Aug 2020, 10:56 AM
Raina Dhankhar
Raina Dhankhar - avatar
+ 10
• String is a class(cannot be mutable),StringBuffer is a thread safe (can be altered). • equals() checks if two objects are the same or not and returns a boolean. • compareTo() (from interface Comparable) returns an integer. It checks which of the two objects is less than,equal to or greater than the other. ... Note that equals() doesn't define the ordering between objects, which compareTo() does. So ,u cant compare string and stringBuffer using compareTo() But u can do other two == (does reference comparision)and equals(object comparition)...but u will get false for both == and equals() because,The equals method of StringBuffer is not overridden from Object, The reason for this is that StringBuffer is modifiable, and overriding equals is mostly useful for value-like classes that you might want to use as keys (though lists also have an overridden equals and StringBuffer is kind of a list, so this is a bit inconsistent. Hope u understand!!
14th Aug 2020, 10:31 AM
chaithra Gowda
chaithra Gowda - avatar
+ 3
Thank you Chaithra Gowda👑 and Raina Dhankhar ...it really helped😊👍🏻
14th Aug 2020, 11:00 AM
Gauri Shirkande
Gauri Shirkande - avatar
+ 1
String str = "Some String"; var sbuff = new StringBuffer("Some String"); System.out.println(str.compareTo(sbuff.toString() ));
14th Aug 2020, 1:23 PM
zemiak