Java String compareTo

The Java compareTo method is one of the String Methods, which compares the string with a user-specified one lexicographically. The comparison is based on the Unicode of the string characters.

This article will show how to write compareTo with an example. The syntax of the String compareTo in Java Programming language is as shown below.

Java String compareTo Syntax

The following compareTo method will accept the String data as an argument and compare both the strings to check whether they are lexicographically equal or not.

public int compareTo(String Str); // It will return integer 

//In order to use in program
String_Object.compareTo(String Str)

The String compareTo method will lexicographically compare the character sequence of String_Object with the character sequence of Str.

  • If the String_Object lexicographically precedes the Str, it will return the result as a Negative Integer.
  • If the String_Object lexicographically follows the Str, it will return the result as Positive Integer.
  • When the String_Object and the string Str are equal, it returns the result as Zero.

Java String compareTo Example

The compareTo method is to compare the string and user-specified data lexicographically. In this program, We are going to do the same. For this, first, we declared four variables.

For a, it will call the public int compareTo (String str) method to compare the str with str2. From the below screenshot, please observe that the function is returning Zero because they both are lexicographical equal.

The following Java statement will compare str with str2. It returns 12 because str has extra 12 character values.

The next String Method statement for c will compare str with str3. It is returning -9 because str3 has extra 9 character values compared to str.

Within the last line, we assigned a sentence directly inside our method. It is returning 32 because the Unicode values of Uppercase & Lowercase letters are different.

package StringFunctions;

public class CompareTo {
	public static void main(String[] args) {
		String str = "Java Programming";
		String str1 = "Java Programming";
		String str2 = "Java";
		String str3 = "Java Programming Language";
		int a = str.compareTo(str1);
		int b = str.compareTo(str2);
		int c = str.compareTo(str3);
		int d = str2.compareTo("Java");
		int e = str2.compareTo("JAVA");

		System.out.println("Comparing the String str and str1 = " + a);
		System.out.println("Comparing the String str and str2 = " + b);
		System.out.println("Comparing the String str and str3 = " + c);
		System.out.println("Comparing the String str2 and Literal = " + d);
		System.out.println("Comparing the String str2 and Literal = " + e);
Java String compareTo Method 1