STRING INSTANCE METHODS

Java String compareTo() method

compareTo() compares two strings lexicographically, using their Unicode character values from left to right. It returns 0, a negative or positive int value.

Comparing identical strings

String pirmas = "Java";
String antras = "Java";

int rezultatas = pirmas.compareTo(antras);

System.out.println(rezultatas);
Console output

0

  1. The variables pirmas and antras store the same text, Java.
  2. pirmas.compareTo(antras) compares the strings character by character.
  3. Since every character matches, the method returns 0.
  4. 0 means the strings are lexicographically equal.

Why is compareTo() an instance method?

compareTo() is called on a specific string because it compares that string with another:

int rezultatas = pirmas.compareTo(antras);

We therefore do not write String.compareTo(...). The left-hand pirmas object is the base string, while antras is supplied as the comparison argument.

Method syntax

public int compareTo(String anotherString)

Parts of the compareTo() method
PartMeaning
Calling objectpirmas in the line pirmas.compareTo(antras)
ParameteranotherString – the string to compare against
Return typeint
Result 0The strings are lexicographically equal
Negative resultThe calling string comes before the argument
Positive resultThe calling string comes after the argument
ErrorNullPointerExceptionwhen the argument is null

Negative and positive results

String pirmas = "Apple";
String antras = "Banana";

System.out.println(pirmas.compareTo(antras));
System.out.println(antras.compareTo(pirmas));
Console output

-1
1

Apple comes before Banana, so "Apple".compareTo("Banana") returns a negative value. Reversing the strings makes the result positive.

The result depends on the first differing character

String pirmas = "abc";
String antras = "abd";

System.out.println(pirmas.compareTo(antras));
Console output

-1

The strings abc and abd match up to the last letter. The letter's c Unicode value is 99, while d value is 100, so the result is 99 - 100, or -1.

When one string is a prefix of the other

String pirmas = "Java";
String antras = "JavaScript";

System.out.println(pirmas.compareTo(antras));
System.out.println(antras.compareTo(pirmas));
Console output

-6
6

If every character of the shorter string matches the start of the longer string, the result depends on the length difference. Java is six characters shorter than JavaScript, so the first comparison returns -6.

Uppercase and lowercase letters differ

String pirmas = "java";
String antras = "Java";

System.out.println(pirmas.compareTo(antras));
Console output

32

compareTo() is case-sensitive. Lowercase j Unicode value is 106and uppercase J value is 74, so "java".compareTo("Java") returns 32.

Using the result in a condition

String pirmas = "Kodas";
String antras = "Pamoka";

int palyginimas = pirmas.compareTo(antras);

if (palyginimas < 0) {
  System.out.println("pirmas tekstas eina anksčiau");
} else if (palyginimas > 0) {
  System.out.println("pirmas tekstas eina vėliau");
} else {
  System.out.println("tekstai vienodi");
}
Console output

pirmas tekstas eina anksčiau

In practice, you rarely need the exact number returned. What matters is whether it is less than 0, equal to 0or greater than 0.

Sorting with compareTo()

import java.util.Arrays;

String[] zodziai = {"Banana", "Apple", "Cherry"};
Arrays.sort(zodziai);

System.out.println(Arrays.toString(zodziai));
Console output

[Apple, Banana, Cherry]

Arrays.sort() sorts a String array in natural string order. Java's String class implements Comparable<String>, so sorting uses the same compareTo() logic.

The argument cannot be null

String tekstas = "Java";
String kitas = null;

System.out.println(tekstas.compareTo(kitas));
Result

NullPointerException

If compareTo() receives null, Java cannot compare text with a nonexistent value. It throws NullPointerException.

Checking safely before comparison

String tekstas = "Java";
String kitas = null;

if (kitas != null) {
  System.out.println(tekstas.compareTo(kitas));
} else {
  System.out.println("Nėra su kuo palyginti");
}
Console output

Nėra su kuo palyginti

If the string to compare may be null, check it first. This avoids a NullPointerException and lets the code display a clear result.

Common mistakes

  • Expecting compareTo() to return true or falsewhen it returns an int.
  • Testing an exact number instead of checking < 0, == 0 or > 0.
  • Forgetting that the method is case-sensitive.
  • compareTo() is used instead of equals()when only an equality check is needed.
  • Passing a null argument to the method.

When should you use compareTo()?

compareTo() Use it to determine string order: sort words, decide which string comes first or implement Comparable logic in your own class. For an equality check, it is usually clearer to use equals(). To ignore letter case, use compareToIgnoreCase().