fastread homefastrread library fastread menu

Java : String compareTo

Tutorial by:Arena Buocel      Date: 2016-04-30 01:05:54

❰ Previous Next ❱

The java string compareTo() method compares the given string with current string lexicographically. It returns positive number, negative number or 0.

If first string is greater than second string, it returns positive number (difference of character value). If first string is less than second string, it returns negative number and if first string is equal to second string, it returns 0.

 
  1. s1 > s2 => positive number  
  2. s1 < s2 => negative number  
  3. s1 == s2 => 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 LastIndexOfExample{  
  2. public static void main(String args[]){  
  3. String s1="hello";  
  4. String s2="hello";  
  5. String s3="meklo";  
  6. String s4="hemlo";  
  7. System.out.println(s1.compareTo(s2));  
  8. System.out.println(s1.compareTo(s3));  
  9. System.out.println(s1.compareTo(s4));  
  10. }}  

Output:

0
-5
-1

❰ Previous Next ❱


Java

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website