Two String can be compared in java with compareTo() method. CompareTo() method returns integer value. This value can be 0 when exactly matched two strings with each others, otherwise it will return in negative and positive value of integer. Use of String CompareTo() in java is shown below.
Example of String CompareTo() in java
public class StringCompareToExample { public static void main(String[] args) { String string_Old="Comparing two java string"; String string_New = "This is new String in java for comparing"; String string_matching = "Comparing two java string"; int returnFlag = string_Old.compareTo(string_New); System.out.println("Comparing string without match :"+returnFlag); int returnFlagWithMatched = string_Old.compareTo(string_matching); System.out.println("Comparing string with match :"+returnFlagWithMatched); } }
Output
Comparing two string objects without match :-17
Comparing two string objects with match :0
Tags: String




Link to Us
Is there any condition about “dictionary order” in compareTo() method.