Java compareTo() Method


The String compareTo() method is used to compares the given string with the invoking string.

The result of the comparison is returned as:

Value Meaning
Less than zero It returns a negative number.
Greater than zero It returns a positive number
Zero It returns zero

Syntax:

 public int compareTo(String str)

Example:

 public class CompareTo
{   
	public static void main(String args[])
    {  
    String s1="Onlinetpoint";  
    String s2="Onlinetpoint";   
    System.out.println(s1.compareTo(s2));  
	if(s1.compareTo(s2)==0)
    {
    	System.out.println("Both the string is equal");
	}
}



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.