Java String compareTo(): Lexicographical Ordering & Unicode Comparison

The String.compareTo() method compares two strings lexicographically based on the Unicode value of each character, returning an int that indicates their dictionary order.

Alphabetical Ranking & Sorting Contracts: While equals() returns a binary true or false, compareTo() determines whether a string comes before (< 0), matches (0), or comes after (> 0) another string. For case-insensitive sorting, explore compareToIgnoreCase(). To discover a character at an index, see charAt(), or inspect total characters with length().

1. Syntax & Method Signature 🔝

The compareTo() method implements the Comparable<String> interface in java.lang.String:

 // Formal signature of String.compareTo() in java.lang.String
public int compareTo(String anotherString)
Returned Value Meaning Lexicographical Interpretation
Negative integer (< 0) str1 < str2 str1 precedes str2 in dictionary order (e.g. "apple" before "banana").
Zero (0) str1.equals(str2) Both strings contain identical character sequences in identical order.
Positive integer (> 0) str1 > str2 str1 follows str2 in dictionary order (e.g. "banana" after "apple").

2. Basic Comparison Examples 🔝

Comparing words demonstrates how Java evaluates alphabetical precedence:

String str1 = "apple";
String str2 = "banana";
String str3 = "apple";

System.out.println("apple vs banana: " + str1.compareTo(str2));  // negative ('a' < 'b')
System.out.println("apple vs apple:  " + str1.compareTo(str3));  // 0 (equal)
System.out.println("banana vs apple: " + str2.compareTo(str1));  // positive ('b' > 'a')

Terminal Output:

apple vs banana: -1
apple vs apple:  0
banana vs apple: 1

3. How compareTo() Calculates Differences 🔝

Java iterates through both strings simultaneously. At the very first index where characters differ, it returns the mathematical difference between their Unicode character codes: this.charAt(k) - anotherString.charAt(k):

String upper = "Welcome to plus2net";
String lower = "welcome to plus2net";

 // 'W' is 87, 'w' is 119 -> 87 - 119 = -32
System.out.println(upper.compareTo(lower));  // -32
System.out.println(lower.compareTo(upper));  // 32

Terminal Output:

-32
32

4. Prefix Matches & Length Differences 🔝

If all characters match up to the length of the shorter string (i.e. one string is a prefix of the other), compareTo() returns the difference in string lengths: this.length() - anotherString.length():

String prefix = "plus2net";
String full = "plus2net.com";

 // "plus2net" len 8, "plus2net.com" len 12 -> 8 - 12 = -4
System.out.println("prefix vs full: " + prefix.compareTo(full));  // -4
System.out.println("full vs prefix: " + full.compareTo(prefix));  // 4
System.out.println("word vs empty:  " + prefix.compareTo(""));     // 8

Terminal Output:

prefix vs full: -4
full vs prefix: 4
word vs empty:  8

5. compareTo() vs. equals(): High-Contrast Comparison 🔝

While both methods can check equality, their purpose and return types differ significantly:

Feature str1.compareTo(str2) str1.equals(str2)
Return Type int (signed integer: < 0, 0, > 0) boolean (true or false)
Primary Purpose Ordering, ranking, and sorting algorithms. Identity and exact content verification.
Interface Contract Implements Comparable<String>. Overrides Object.equals().
Parameter Type Strictly String anotherString. Accepts any Object anObject.
String word1 = "Java";
String word2 = "java";

System.out.println("equals():    " + word1.equals(word2));  // false

int result = word1.compareTo(word2);
System.out.println("compareTo(): " + result);  // -32

if (result < 0) {
    System.out.println(""Java" precedes "java" in Unicode order.");
} else if (result > 0) {
    System.out.println(""Java" follows "java" in Unicode order.");
} else {
    System.out.println("Strings are identical.");
}

Terminal Output:

equals():    false
compareTo(): -32
"Java" precedes "java" in Unicode order.

6. compareTo() vs. compareToIgnoreCase() 🔝

In standard compareTo(), uppercase letters strictly precede lowercase letters because ASCII 'A' (65) is less than 'a' (97). Use compareToIgnoreCase() when case should not affect sorting:

String a = "ORANGE";
String b = "orange";

 // compareTo(): Case-sensitive (Upper 'O' < Lower 'o')
System.out.println("compareTo():           " + a.compareTo(b));            // -32

 // compareToIgnoreCase(): Case-insensitive
System.out.println("compareToIgnoreCase(): " + a.compareToIgnoreCase(b));  // 0

Terminal Output:

compareTo():           -32
compareToIgnoreCase(): 0

7. Null Handling & NullPointerException 🔝

Unlike equals() (which safely returns false when passed null), passing null into compareTo() immediately throws a NullPointerException. Always validate references prior to calling compareTo():

String current = "plus2net";
String other = null;

try {
    System.out.println(current.compareTo(other));
} catch (NullPointerException e) {
    System.out.println("Caught NullPointerException!");
}

 // Null-safe helper: handles null references safely
int cmp = (other == null) ? 1 : current.compareTo(other);
System.out.println("Safe comparison: " + cmp);

Terminal Output:

Caught NullPointerException!
Safe comparison: 1

8. Production Recipe: Sorting String Arrays & Lists 🔝

Java's sorting utilities (Arrays.sort() and Collections.sort()) use compareTo() under the hood to position elements alphabetically:

import java.util.Arrays;

public class AlphabeticalSorting {
    public static void main(String[] args) {
        String[] fruits = {"Mango", "Apple", "Banana", "Orange", "Cherry"};

         // Arrays.sort() uses compareTo() under the hood
        Arrays.sort(fruits);

        System.out.println("Sorted fruits: " + Arrays.toString(fruits));
    }
}

Terminal Output:

Sorted fruits: [Apple, Banana, Cherry, Mango, Orange]

9. Common Developer Pitfalls & Traps 🔝

The Exact -1 or +1 Return Trap

Never write if (s1.compareTo(s2) == -1). Java's specification only guarantees a negative integer, not specifically -1. For example, "a".compareTo("c") returns -2. Always check < 0 or > 0.

The Uppercase Alphabetical Sort Trap

Because ASCII uppercase letters (65–90) have lower Unicode codes than lowercase letters (97–122), "Zebra".compareTo("apple") returns a negative number. "Zebra" sorts before "apple" unless using compareToIgnoreCase().

10. Complete Compilable Java Program 🔝

You can compile and run this complete Java demonstration class locally to verify all compareTo() behaviors:

public class StringCompareToFullDemo {
    public static void main(String[] args) {
        String s1 = "alpha";
        String s2 = "beta";
        String s3 = "alpha";

         // 1. Equal strings return 0
        if (s1.compareTo(s3) == 0) {
            System.out.println("Check 1 Passed: Identical strings return 0.");
        }

         // 2. Lexicographical ordering
        if (s1.compareTo(s2) < 0) {
            System.out.println("Check 2 Passed: 'alpha' precedes 'beta' (negative value).");
        }

         // 3. Prefix length calculation
        String base = "data";
        String extended = "database";
        if (base.compareTo(extended) == -4) {
            System.out.println("Check 3 Passed: Prefix difference equals length gap (-4).");
        }

        System.out.println("All String.compareTo() verification checks passed successfully!");
    }
}

Terminal Output:

Check 1 Passed: Identical strings return 0.
Check 2 Passed: 'alpha' precedes 'beta' (negative value).
Check 3 Passed: Prefix difference equals length gap (-4).
All String.compareTo() verification checks passed successfully!

11. Frequently Asked Questions (FAQ) 🔝

Why does "a".compareTo("c") return -2 instead of -1?

Unicode code for 'a' is 97 and 'c' is 99. The method performs 97 - 99 = -2. The magnitude reflects the distance between characters in the Unicode table.

Does compareTo() work with StringBuffer or StringBuilder?

No. String.compareTo() strictly requires a String argument. Convert the buffer first with .toString().

What happens when comparing a string to an empty string?

Since the empty string "" is a prefix of every string, str.compareTo("") returns the exact length of str.

Can compareTo() be used in an if statement directly?

Because compareTo() returns an int rather than a boolean, it must be paired with relational operators: if (s1.compareTo(s2) == 0) or if (s1.compareTo(s2) < 0).

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer