I was checking the string comparison methods used for string compsrsion and explore the string class in the decomplier and come to know that there are basically four methods
equals()
equalsIgnoreCase()
compareTo()
compareToIgnore()
Now I want to know the difference between two methods that we use they are equals() and compareTo() , basically please advise why string class had kept both these methods ..
String tv = "Bravia";
String television = "Bravia";
// String compare example using equals
if (tv.equals(television)) {
System.out.println("Both tv and television contains same letters and equal by equals method of String");
}
// String compare example in java using compareTo
if (tv.compareTo(television) == 0) {
System.out.println("Both tv and television are equal using compareTo method of String");
}
output :-
Both tv and television contains same letters and equal by equals method of String
Both tv and television are equal using compareTo method of String
Strings implement Comparable interface and then its bound to implement compareTo method.
Camparable interface
it facilitates ordering of the object when they are contained in any sorted collection. So when you will put your string in any sorted collection(like TreeSet), how will you tell java how to sort your objects. that’s where coompareTo() method comes in seen. it is used by collection to sort your object.