Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
What Is compareTo() in Java?
The compareTo() method compares two strings lexicographically. Each character is converted to its Unicode value, and the method returns an int that indicates the relative ordering. If the strings are identical, it returns 0; otherwise, the result is negative if the first string precedes the second, or positive if it follows.
This method is defined in the java.lang.Comparable interface.
Syntax
public int compareTo(String str)
Parameter: str – the string to compare with the calling string.
Return Value: An int that is negative, zero, or positive depending on the lexicographical order.
< 0– the calling string is lexicographically first.== 0– the two strings are equal.> 0– the argument string is lexicographically first.
Example 1: Basic Usage
public class SampleString {
public static void main(String[] args) {
String str = "a";
System.out.println("Compare \"a\" to \"b\": " + str.compareTo("b"));
str = "b";
System.out.println("Compare \"b\" to \"a\": " + str.compareTo("a"));
str = "b";
System.out.println("Compare \"b\" to \"b\": " + str.compareTo("b"));
}
}
Output
- Compare "a" to "b": -1
- Compare "b" to "a": 1
- Compare "b" to "b": 0
Explanation:
- “a” comes before “b” alphabetically, so the result is negative.
- “b” comes after “a”, producing a positive result.
- Identical strings yield zero.
Example 2: Case‑Sensitive vs. Case‑Insensitive
public class SampleString {
public static void main(String[] args) {
String str = "RockStar";
System.out.println("Case‑sensitive compare to \"rockstar\": " + str.compareTo("rockstar"));
System.out.println("Case‑insensitive compare to \"ROCKSTAR\": " + str.compareToIgnoreCase("ROCKSTAR"));
}
}
Output
- Case‑sensitive compare to "rockstar": -32
- Case‑insensitive compare to "ROCKSTAR": 0
When to Use compareTo()
Use compareTo() when you need natural (lexical) ordering of strings, such as sorting a list of names or performing dictionary lookups. The method follows the same rules as the String.compareToIgnoreCase() method but respects case.
Typical scenarios include:
- Sorting collections of
Stringobjects withCollections.sort(). - Implementing
Comparablein custom classes that need string comparison. - Performing binary search on sorted string arrays.
Example 3: Practical Comparison
public class CompareDemo {
public static void main(String[] args) {
String s1 = "Guru1";
String s2 = "Guru2";
System.out.println("String 1: " + s1);
System.out.println("String 2: " + s2);
int result = s1.compareTo(s2);
if (result < 0) {
System.out.println("\"" + s1 + "\" is lexicographically higher than \"" + s2 + "\"");
} else if (result == 0) {
System.out.println("\"" + s1 + "\" is lexicographically equal to \"" + s2 + "\"");
} else {
System.out.println("\"" + s1 + "\" is lexicographically less than \"" + s2 + "\"");
}
}
}
Output
- String 1: Guru1
- String 2: Guru2
- "Guru1" is lexicographically higher than "Guru2"
Java
- Mastering C# Queues: Enqueue, Dequeue, and First‑In‑First‑Out Operations Explained
- Java ArrayList Explained: Usage, Key Methods, and Practical Examples
- Java String length() Method: How to Get a String’s Size (Example)
- Mastering Java String.indexOf(): Locating Substrings & Practical Examples
- Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
- Java String.contains() Method: How to Check for Substrings – Practical Examples
- Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
- Mastering Java's split() Method: A Practical Guide with Code Examples
- Converting a Char to a String in Java – Practical Examples and Best Practices
- Master Python's String.find() Method: Syntax, Examples & Alternatives