Java String compareTo() method explained | technical-arbaab

 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));  
      }  
 }  
Output:
 -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));  
      }  
 }  
Output:
 1  
 7  
here, you see that the string s1 Unicode value (ASCII or decimal value) of character is greater than string s2 character Unicode value hence it returns 1 (positive) and in string s3 and s4 "k" ASCII value is greater than "d" ASCII value hence it returns a positive number 7 (difference of ASCII values), if you are thinking about how to find the ASCII value of characters in Java click on in it "how to check the ASCII values of characters in Java".



Comments