Java String compareTo() Method with Examples
The `compareTo()` method in Java is used to compare two strings lexicographically. It returns an integer value which can be either negative, zero or positive depending on whether the first string is lexicographically smaller, equal or greater than the second string. This article will explain the concept with an example and also discuss the different cases where the method can be used.
In lexicographical order, the characters at the same position in the two strings are compared. If they are same, the comparison goes to the next character in both strings. If they are different, the comparison stops and the result is based on the character at the current position.
The `compareTo()` method can be used to sort strings in alphabetical order. It can be used to compare the strings and to check if two strings are equal. The method returns an integer which is the difference between the ASCII values of the characters in the two strings. If the returned value is 0, it means that the two strings are equal. If it is a positive or negative number, it means that the two strings are not equal.
The `compareTo()` method can be used to search for a particular string in a list of strings. It can also be used to compare two strings for their length. This method is case sensitive which means that strings with different cases will be treated as different.
Worried About Failing Tech Interviews?
Attend our webinar on
"How to nail your next tech interview" and learn
.png)
Hosted By
Ryan Valles
Founder, Interview Kickstart

Our tried & tested strategy for cracking interviews

How FAANG hiring process works

The 4 areas you must prepare for

How you can accelerate your learnings
Register for Webinar
The Java String compareTo() method is used to compare two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns an integer value which is:
- **Less than** 0, if the String object comes before the argument
- **Equal to** 0, if the String object is equal to the argument
- **Greater than** 0, if the String object comes after the argument
### Syntax
```
int compareTo(String anotherString)
```
### Parameters
- **anotherString**: The String to be compared.
### Returns
The value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.
### Example
```
// Java program to illustrate compareTo()
public class CompareToExample {
public static void main(String args[])
{
String s1 = "Hello World";
String s2 = "Hello World";
String s3 = "Hello";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
}
}
// Output
0
5
```