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 a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.