Java String compare To() method
It is a predefined function which is present in the Java.lang.String package. It is used to compare two strings lexicographically confusing word don't worry we are here to clear, It means we compare the decimal value of a string or unicode value (ASCII value) of a string for example 'a' decimal value is 97 and 'A' decimal value is 65 so we compare both the values and returns the integer which is the difference between these two values hope it is clear for example-
If there are two strings s1 and s2 then
if s1>s2 // it returns a positive number
if s1<s2 // it returns a negative number
if s1=s2 // it returns zero
Syntax of compare To() function
int compareTo(another string);
Implementation of compare To() function
Example 01-
public class strings05 {
public static void main(String[] args)
{
String s1 = "a";// decimal value is 97
String s2 = "A";// decimal value is 65
System.out.println(s1.compareTo(s2));
}
}
Output:
32
here, as you see that 32 is returned because small "a" decimal value is greater than capital "A" decimal value so the difference is 32 and positive, let's see an another case-
Example 02-
public class strings05 {
public static void main(String[] args)
{
String s1 = "Jack";// decimal value is 97
String s2 = "Jacl";// decimal value is 65
System.out.println(s1.compareTo(s2));
}
}
-1
you must be wondering what happened when you provide the sequence of characters what value it will compare to check the the difference between decimal value so it will compare letter by letter, during comparison of the strings the very first letter which is different of both the strings is checked here in this example "k" and "l" value is checked in decimal values and rest is same.
Example 03-
public class strings05 {
public static void main(String[] args)
{
String s1 = "J";// decimal value is 97
String s2 = "";// decimal value is 65
System.out.println(s1.compareTo(s2));
String s3 = "Rocky";
String s4 = "Rocdy";
System.out.println(s3.compareTo(s4));
}
}
1
7
Hello, visitor your comments are so helpful for us so do not hesitate just write the comment we read all your comments so don't think your comment goes waste.