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 character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string.

Signature of compareTo() Method:
String compareTo(String anotherString)

Suppose str1 and str2 are two strings.
int s1 = str1.compareTo(str2);

if s1 > 0 , then String object str1 lexicographically follows str2.
if s1 < 0 , then String object str1 lexicographically precedes str2. if s1 = 0 , then String object str1 is equal to str2. Let's take an example to understand this.

Example : String compareTo() Method
package com.masterjavatutorial;
public class TestExample {
	public static void main(String[] args) {
        String str = "abc";
        String str1 = "bcd";
        
        int s1 = str.compareTo(str1);
        System.out.println("s1 = "+s1);
        
        String str2 = "abc";
        String str3 = "abc";
        
        int s2 = str2.compareTo(str3);
        System.out.println("s2 = "+s2);

        String str4 = "gh";
        String str5 = "bcd";
        
        int s3 = str4.compareTo(str5);
        System.out.println("s3 = "+s3);

	}
}

Output of the above program is as below:

s1 = -1
s2 = 0
s3 = 5