Compare strings


Hello everyone. This page is an English translation of a Japanese page. (The original Japanese has been slightly rewritten to make it easier to translate into English.)

This time, I used the String#compareTo method to compare strings. To be precise, it is the following method.

  • public int compareTo(String anotherString)

This method compares the String object itself with its argument anotherString in lexicographic order. This method returns an integer value.

If the String object is before, the same as, or behind the argument string in the dictionary expression order, this method returns a negative, zero, or positive number, respectively.

This is what the first half of the API specification description says. The second half looks complicated, but roughly written, it is as follows

  1. If the lengths are equal, return the difference between the i-th in the char array.
  2. If the lengths are different, return the difference in string lengths.

In this article, we will look at the above two movements.

Compare with string “abc"

This time, I ran the following program as an experiment. It compares the string “abc" with various other strings.

public class HelloCompareTo {

	public static void main(String[] args) {
		String str = "abc";




Execution results


The first half of the results are summarized in the table below.

Argument Returned value
aba 2
abb 1
abc 0
abd -1
abe -2
abf -3

The string being compared to “abc" all consists of three characters.
Since the first two characters are equal, the output result is the difference in the character code of the third character.

The second half of the output shows the difference in the number of characters. If the string is the same from the beginning to the middle, the shorter string is in the previous position in the order of the dictionary expression.

In the case of a null argument

If the argument of this method is an empty string, no error will occur, but if it is null, an error will occur. I have tried the following.

public class HelloCompareToEtc {

	public static void main(String[] args) {
		String str = "abc";


Execution results
Exception in thread "main" java.lang.NullPointerException
	at java.lang.String.compareTo(
	at source0005.HelloCompareToEtc.main(

I read the source of the method. I couldn’t find anything to check if the argument is null. In other words, if the argument of this method is null, a NullPointerException will be thrown.

Knowing this method, it is likely that you would write “a.compareTo(b) == 0" to determine that the strings are equal. Note that there is an equals method for such a case. In Java, strings are objects of the string class. Use the equals method to check if the objects are equal or not. ((However, the class needs to override the equals method correctly. Be careful if you haven’t created an equals method in your own class.)

That’s all. I hope this is helpful to you.

Articles next and previous in the same category