Java String compareTo() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

The compareTo() method compares two strings in lexicographic order (like dictionary order) and returns an int telling you which string comes first. It is the standard tool for sorting strings and the basis of Java’s Comparable interface.

01

Dictionary Order

Lexicographic compare.

02

Returns int

Negative, zero, or positive.

03

Case Sensitive

A ≠ a in ordering.

04

Sorting

Lists, arrays, TreeSet.

05

vs equals()

Order vs equality.

06

Unicode Based

Chars, digits, symbols.

Definition and Usage

In Java, compareTo(String anotherString) compares the calling string with the argument string character by character, using Unicode values. If the first differing character in the caller is smaller, the result is negative; if larger, positive; if no difference is found and both strings have the same length, the result is zero.

For example, "apple".compareTo("banana") returns a negative number because 'a' comes before 'b'. This is how Java naturally sorts names in a contact list or words in a vocabulary app.

💡
Beginner Tip

You usually care about the sign of the result (< 0, == 0, > 0), not the exact number. Write if (s1.compareTo(s2) < 0) rather than checking for exactly -1.

📝 Syntax

The compareTo() method is declared in the String class:

java
public int compareTo(String anotherString)

Parameters

  • anotherString — the string to compare against. Must not be null (passing null throws NullPointerException).

Return Value

  • Negative — the calling string is lexicographically less than the argument.
  • Zero — both strings are lexicographically equal.
  • Positive — the calling string is lexicographically greater than the argument.

⚡ Quick Reference

ExpressionResult signMeaning
"apple".compareTo("banana")Negativeapple comes first
"banana".compareTo("apple")Positivebanana comes after
"java".compareTo("java")ZeroEqual order
"app".compareTo("apple")NegativeShorter shared prefix
"Apple".compareTo("apple")NegativeCase matters ('A' < 'a')
Less than
s1.compareTo(s2) < 0

s1 before s2

Equal order
s1.compareTo(s2) == 0

Same sequence

Greater
s1.compareTo(s2) > 0

s1 after s2

Sort list
Collections.sort(list)

Uses compareTo internally

Examples Gallery

These programs run in Java 8+. They cover basic comparison, equal strings, sorting, case sensitivity, and prefix length rules.

📚 Getting Started

Compare two fruit names and interpret the result.

Example 1 — Basic Lexicographic Comparison

Determine whether "apple" comes before or after "banana" in dictionary order.

java
public class CompareExample {
    public static void main(String[] args) {
        String str1 = "apple";
        String str2 = "banana";

        int result = str1.compareTo(str2);

        if (result < 0) {
            System.out.println("str1 is before str2");
        } else if (result > 0) {
            System.out.println("str1 is after str2");
        } else {
            System.out.println("str1 and str2 are equal");
        }
        System.out.println("compareTo returned: " + result);
    }
}

How It Works

Both strings share no useful prefix difference at index 0: 'a' vs 'b'. Since 'a' (97) is less than 'b' (98), compareTo returns a negative value. The exact value (-1 here) is an implementation detail.

Example 2 — Equal Strings Return Zero

When both strings contain the same characters in the same order, compareTo() returns 0.

java
public class CompareEqual {
    public static void main(String[] args) {
        String a = "Java";
        String b = "Java";

        System.out.println("compareTo: " + a.compareTo(b));
        System.out.println("equals:    " + a.equals(b));
    }
}

How It Works

Zero from compareTo() means lexicographic equality. For strings, that also implies equals() is true. The reverse is also true: if compareTo returns 0, the character sequences match.

📈 Practical Patterns

Sorting, case rules, and strings that share a prefix.

Example 3 — Sort Names with compareTo()

Collections.sort uses natural ordering, which for strings means compareTo().

java
import java.util.Arrays;
import java.util.List;

public class SortNames {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Mari", "Arun", "Zara", "Bala");

        names.sort(String::compareTo);

        System.out.println(names);
    }
}

How It Works

Each pair of names is compared with compareTo() during sorting. The result list is in ascending lexicographic (A–Z) order. This is the most common real-world use of the method.

Example 4 — Case Sensitivity

Uppercase letters sort before lowercase in Unicode, so case changes the outcome.

java
public class CaseCompare {
    public static void main(String[] args) {
        String upper = "Apple";
        String lower = "apple";

        System.out.println("\"Apple\".compareTo(\"apple\"): " +
            upper.compareTo(lower));
        System.out.println("\"apple\".compareTo(\"Apple\"): " +
            lower.compareTo(upper));
    }
}

How It Works

The first characters differ: 'A' (65) vs 'a' (97). The difference is 32 at that position, which becomes the return value. For case-insensitive sorting, use compareToIgnoreCase() instead.

Example 5 — Shared Prefix and Different Lengths

When one string is a prefix of another, the shorter string compares as smaller.

java
public class PrefixCompare {
    public static void main(String[] args) {
        String shortWord = "app";
        String longWord  = "apple";

        System.out.println("\"app\".compareTo(\"apple\"):  " +
            shortWord.compareTo(longWord));
        System.out.println("\"apple\".compareTo(\"app\"): " +
            longWord.compareTo(shortWord));
    }
}

How It Works

The first three characters match. "app" runs out of characters first, so it is considered smaller—like "car" vs "card" in a dictionary. Java returns the length difference at the point the strings diverge.

🚀 Common Use Cases

  • Sorting data — order usernames, product names, or file paths alphabetically.
  • Ordered collectionsTreeSet and TreeMap rely on comparison logic like compareTo().
  • Binary search — find a string in a sorted array efficiently.
  • Range checks — test whether a value falls between two string bounds.
  • Implementing Comparable — custom classes often delegate string fields to compareTo().

🧠 How compareTo() Works

1

Start at index 0

Java compares the first character of each string, then the second, and so on.

Scan
2

First difference wins

When characters differ, return thisChar - otherChar at that position.

Compare
3

Same prefix? Check length

If one string is a prefix of the other, the shorter string is considered smaller.

Length
=

int result

Negative, zero, or positive—your sort-order signal.

📝 Notes

  • Comparison is case-sensitive. Use compareToIgnoreCase() when case should not affect order.
  • Ordering follows Unicode code unit values, so digits and symbols participate normally.
  • Passing null as the argument throws NullPointerException.
  • compareTo() == 0 implies the strings are equal in content; use equals() when you only need a true/false equality check.
  • Do not rely on the exact numeric result—only the sign is guaranteed to be meaningful.

⚡ Optimization

compareTo() is the standard, optimized way to compare strings in Java. It stops at the first differing character rather than scanning the entire string when possible. For sorting large lists, prefer built-in sort utilities (Collections.sort, Arrays.sort) that call compareTo() efficiently rather than writing nested loops by hand.

Conclusion

The compareTo() method is Java’s built-in way to answer “which string comes first?” It powers sorting, ordered collections, and any logic that depends on dictionary-style ordering.

Remember the three outcomes: negative (before), zero (equal), positive (after). Watch out for case sensitivity and prefix-length rules, and reach for compareToIgnoreCase() when uppercase and lowercase should sort together.

💡 Best Practices

✅ Do

  • Check the sign: < 0, == 0, > 0
  • Use Collections.sort for ordering lists of strings
  • Use compareToIgnoreCase() for case-insensitive order
  • Guard against null before comparing
  • Use equals() when you only need equality, not order

❌ Don’t

  • Compare strings with == (compares references, not content)
  • Assume the return value is always exactly -1, 0, or 1
  • Use compareTo() when you mean locale-aware human sorting
  • Pass null as the argument string
  • Confuse lexicographic order with numeric order ("10" < "2")

Key Takeaways

Knowledge Unlocked

Five things to remember about compareTo()

Use these points whenever you sort or order strings in Java.

5
Core concepts
🔢 02

Sign Matters

< 0, 0, or > 0.

Return
🔑 03

Case Sensitive

A before a in ASCII.

Edge case
📈 04

Sorting

Lists and TreeSet.

Use case
🔄 05

Not equals()

Order vs equality.

Compare

❓ Frequently Asked Questions

compareTo(String anotherString) compares two strings lexicographically (dictionary order) based on Unicode values of their characters. It returns a negative int if the calling string comes first, zero if they are equal, or a positive int if the calling string comes after.
Call it on a String: string1.compareTo(string2). It takes one String argument and returns an int. The method is defined in java.lang.String and is part of the Comparable interface.
A negative value means the caller is less than the argument. Zero means both strings are lexicographically equal. A positive value means the caller is greater. The exact number (e.g. -1 vs -25) usually does not matter—only the sign.
No. equals() checks whether two strings have the same content (equality). compareTo() determines sort order (ordering). Two strings can be unequal by equals yet still compare as ordered, and compareTo() == 0 implies equals() is true for strings.
Yes. Uppercase letters have lower Unicode values than lowercase in ASCII, so "Apple" and "apple" compare differently. Use compareToIgnoreCase() when case should not matter.
Use it for sorting lists of strings, building ordered collections like TreeSet, binary search on sorted data, and any logic that needs before/after/equal ordering rather than simple equality.

Keep Exploring Java String Methods

Now that you can compare strings with compareTo(), revisit character access methods to build complete text-processing skills.

Next: compareToIgnoreCase() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful