Thursday, 13 July 2017

String compareTo() in java ~ foundjava

Java String compareTo()

The java string compareTo() method compares the given string with current string lexicographically. It returns positive number, negative number or 0.
It compares strings on the basis of Unicode value of each character in the strings.
If first string is lexicographically greater than second string, it returns positive number (difference of character value). If first string is less than second string lexicographically, it returns negative number and if first string is lexicographically equal to second string, it returns 0.
  1. if s1 > s2, it returns positive number  
  2. if s1 < s2, it returns negative number  
  3. if s1 == s2, it returns 0  

Signature

  1. public int compareTo(String anotherString)  

Parameters

anotherString: represents string that is to be compared with current string

Returns

an integer value

Java String compareTo() method example

  1. public class CompareToExample{  
  2. public static void main(String args[]){  
  3. String s1="hello";  
  4. String s2="hello";  
  5. String s3="meklo";  
  6. String s4="hemlo";  
  7. String s5="flag";  
  8. System.out.println(s1.compareTo(s2));//0 because both are equal  
  9. System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"  
  10. System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"  
  11. System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"  
  12. }}  

Output:
0
-5
-1
2

Java String compareTo(): empty string

If you compare string with blank or empty string, it returns length of the string. If second string is empty, result would be positive. If first string is empty, result would be negative.
  1. public class CompareToExample2{  
  2. public static void main(String args[]){  
  3. String s1="hello";  
  4. String s2="";  
  5. String s3="me";  
  6. System.out.println(s1.compareTo(s2));  
  7. System.out.println(s2.compareTo(s3));  
  8. }}  

Output:
5
-2

No comments:

Post a Comment