Java String compareTo Method With Programming Examples

In this Tutorial, we will Learn about the Java String compareTo() Method and see how and when to use compareTo in Java Along with Syntax and Examples:

You will understand how to manipulate Java String with help of compareTo() Java method. The output types which we will get through Java compareTo() method will also be covered in this tutorial.

After reading this tutorial, you will definitely be able to understand and write the Java String programs that require .compareTo() method for String manipulation.

=> Check Out The Perfect Java Training Guide Here.

Java String CompareTo

Java String compareTo() Method

The Java String compareTo() method is used to check whether two Strings are identical or not. As the name suggests, it compares two given Strings and finds out if they are the same or which one is greater.

The return type of Java compareTo() method is an integer and the syntax is given as:

 int compareTo(String str)

In the above syntax, str is a String variable that is being compared to the invoking String.

For example: String1.compareTo(String2);

Another variation of Java compareTo() is

 int compareTo(Object obj)

In the above syntax, we will compare a String with an Object obj.

For example, String1.compareTo(“This is a String Object”);

Here “This is a String Object” is an argument that we are passing to the compareTo() and it compares that with String1.

Java compareTo() Method Output Types

The output has three types that are based on the output value.

Below is the table that explains all the three types of output values.

compareTo() Output ValueDescription
ZeroTwo Strings are equal.
Greater than ZeroThe invoking String is greater than str.
Less than ZeroThe invoking String is less than str.

Let’s understand these three variants in detail with the help of an example.

A Programming Example

Here is an example of compareTo() Java method. The comparison is based on the difference in the ASCII value of the characters. In general terms, a String is less than the other if it comes before the other in the dictionary.

package codes;
import java.lang.String;

public class CompareTo {

	public static void main(String[] args) {
		
		String str1 = "Grand Theft Auto";
		String str2 = "Assassin Creed";
		String str3 = "Call of Duty";
		String str4 = "Need for Speed";
		String str5 = "Grand Theft Auto";
		
		System.out.println(str1.compareTo(str2));
		// Since 'A' is greater than 'G' by 6 characters, so it will return 6
		
		System.out.println(str2.compareTo(str3));
		// Since 'C' is smaller than 'A' by 2 characters, so it will return -2
		
		System.out.println(str3.compareTo(str4));
		//Since 'N' is smaller than 'C' by 11 characters, so it will return -11
		
		System.out.println(str4.compareTo(str1));
		//Since 'G' is Greater than 'N' by 7 characters, so it will return 7
		
		System.out.println(str1.compareTo(str5));
		//Strings are equal
		
	}
}

Output:

Java CompareTo - A programming example

Explanation of Example

In the above example, we have taken five input Strings and performed a basic comparison between them using the .compareTo() Java method. In the first comparison, we have ‘A’ greater than ‘G’ by 6 characters in the alphabet series, so it returns +6. In the second comparison, we have ‘C’ smaller than ‘A’ by 2 characters, so it returns -2.

In the last comparison (between str1 and str5), as both the Strings are equal, it returns 0.

Various Scenarios

Let’s understand .compareTo() method in detail. Here we will try to analyze different scenarios and the output of each case.

Scenario1: Consider the following two Strings. We will compare them and see the output.

String str1 = “Software Testing”;
String str2 = “Software Testing Help”;

What will be the output of str1.compareTo(str2)?

Answer: As str2 contains 5 characters (one space + four characters) more than the first String. The output should be -5. Similarly, when we compare str2 with str1, the output should be +5.

package codes;
import java.lang.String;

public class CompareTo {

	public static void main(String[] args) {
		
		String str1 = "Software Testing";
		String str2 = "Software Testing Help";
		
		System.out.println(str1.compareTo(str2));
		// Since str2 contains 5 characters more than the str1, output should be -5
		
		System.out.println(str2.compareTo(str1));
		// Since str2 contains 5 characters less than the str1, output should be +5
	}
}

Output:

Output - Scenario1

Scenario2: Consider the following two Strings. We will compare them and see the output.

String str1 = “”;
String str2 = ” “;

What will be the output of str1.compareTo(str2)?

Answer: As str2 contains one character (space) more than the str1, it should give the output as -1.

package codes;
import java.lang.String;

public class CompareTo {

	public static void main(String[] args) {
		
		String str1 = "";
		String str2 = " ";
		
		System.out.println(str1.compareTo(str2));
		//Since str2 contains one character more than str1, it will give -1
		System.out.println(str2.compareTo(str1));
		//Since str1 contains one character less than str1, it will give 1
		
	}
}

Output:

Java CompareTo - Scenario2

Scenario3: Consider the following two Strings. We will compare them and see the output.

String str1 = “SAKET”;
String str2 = “saket”;

What will be the output of str1.compareTo(str2)?

Answer: Here the Strings are equal but str1 has uppercase whereas str2 has lowercase. This was the limitation of the Java compareTo() method. The output which we will get will be a non-zero. To overcome this problem, Java introduced another variation of .compareTo() method which is

.compareToIgnoreCase()

package codes;
import java.lang.String;

public class CompareTo {

	public static void main(String[] args) {
		
		String str1 = "SAKET";
		String str2 = "saket";

		System.out.println(str1.compareTo(str2));
		//The ASCII representation of the lowercase and uppercase has a difference of 32
		
	}
}

Output:

Output - Scenario3

Java String compareToIgnoreCase() Method

As we have discussed the problem in the case mismatch (Scenario3), we already have another variant of .compareTo() method which will ignore the case mismatch of the Strings.

Syntax of this method is given as

int compareToIgnoreCase(String str)

Everything else remains the same except the fact that .compareToIgnoreCase() does not take the case mismatch into consideration.

A Programming Example

Here is an example of compareTo() Java method. In this example, we have illustrated the difference in the outputs of Java compareTo() and compareToIgnoreCase(). Java compareTo() will give a difference of -32 whereas compareToIgnoreCase() will give a difference of 0.

package codes;

public class CompareToIgnoreCase {

	public static void main(String[] args) {
		String str1 = "SAKET";
		String str2 = "saket";

		System.out.println(str1.compareTo(str2));
		System.out.println(str1.compareToIgnoreCase(str2));
	}

}

Output:

Example - Java Compare ToIgnore Case

Explanation of Example:

In the above example, we have taken two Strings that have the same value keeping one String in Uppercase and another one in Lowercase. Now, a Java .compareTo() method will provide results based on the ASCII difference in the value of the Lowercase and Uppercase as it will take the character case into consideration.

But Java .compareToIgnoreCase() won’t take the character case into consideration and will give a result as 0 which means both the Strings are equal.

Frequently Asked Questions

Q #1) What is the difference between ==, equals and .compareTo()?

Answer: Enlisted below are the main differences between ==, equals() and compareTo().

!ERROR! unexpected operator '='equals()compareTo()
!ERROR! unexpected operator '='equals() is a method.compareTo() is a method.
!ERROR! unexpected operator '='equals() method does the content comparison.compareTo() does the comparison based on ASCII value.
The return type is Boolean.The return type is Boolean.The return type is Integer.
It uses the reference of the String variable, so memory addresses should be the same when comparing.It does not require the objects to be logically ordered.It requires the objects to be logically ordered.

Here is a programming example illustrating the difference.

package codes;

public class CompareToIgnoreCase {

	public static void main(String[] args) {
		String str1 = new String("Testing");
		String str2 = "Testing";

		System.out.println(str1.compareTo(str2));
		System.out.println(str1 ==str2);
		System.out.println(str1.equals(str2));
	}

}

Output:

Java CompareTo - FAQ1

Q #2) Is Java compareTo() method case-sensitive?

Answer: Yes. Java .compareTo() method considers the characters case and it is case-sensitive.

Below is the illustration.

package codes;

public class CompareToIgnoreCase {

	public static void main(String[] args) {
		String str1 = "Software";
		String str2 = "SOFTWARE";

		System.out.println(str1.compareTo(str2));
		
	}

}

Output:

Is Java CompareTo Case Sensitive?

Q #3) How does compareTo() work in Java?

Answer: Java compareTo() method actually compares the ASCII values of the characters of a String.

Let us say that we are going to compare a comma and a space character using the .compareTo() method. As we know, a space character has an ASCII value 32 whereas a comma has an ASCII value 44. The difference between the ASCII value of space and comma is 12.

Below is the programming example.

package codes;

public class CompareTo {

	public static void main(String[] args) {
		String str1 = ",";
		String str2 = " ";

		System.out.println(str1.compareTo(str2));
		
	}

}

Output:

Working of Java CompareTo

Q #4) How to find the length of a String by using Java .compareTo() method?

Answer: Given below is the program to find the length of a string by using the Java .compareTo() method.

In this example, we have taken one String whose length we have to find and an empty String. Then we have compared the String with the empty String. The difference between them will be the length of the String.

package codes;

public class CompareTo {

	public static void main(String[] args) {
		String str1 = "Tony Stark";
		String str2 = "";

		System.out.println(str1.compareTo(str2));
		
	}

}

Output:

Length of a string

Q #5) What does the compareTo method return?

Answer: Java compareTo() method's return type is integer. The integer value can be zero, positive integer or negative integer.

Conclusion

In this tutorial, we have understood the Java String compareTo() method in detail. The basic functionality, details about the implementation, and the usage especially the programming examples were provided for a better understanding of the concept related to the String compareTo() method.

Using this method, you can compare two Strings and a lot of other usages or application areas like finding the length of the String is also possible with the help of the compareTo() method which has been covered in the frequently asked questions.

=> Visit Here For The Exclusive Java Training Tutorial Series.