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);0
- The variables
pirmasandantrasstore the same text, Java. pirmas.compareTo(antras)compares the strings character by character.- Since every character matches, the method returns
0. 0means 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)
| Part | Meaning |
|---|---|
| Calling object | pirmas in the line pirmas.compareTo(antras) |
| Parameter | anotherString – the string to compare against |
| Return type | int |
Result 0 | The strings are lexicographically equal |
| Negative result | The calling string comes before the argument |
| Positive result | The calling string comes after the argument |
| Error | NullPointerExceptionwhen 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));-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));-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));-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));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");
}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));[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));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");
}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 returntrueorfalsewhen it returns anint. - Testing an exact number instead of checking
< 0,== 0or> 0. - Forgetting that the method is case-sensitive.
compareTo()is used instead ofequals()when only an equality check is needed.- Passing a
nullargument 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().