CompareTo Orders By Code Unit

String.compareTo compares UTF-16 code units one position at a time, so uppercase letters sort before lowercase and prefixes yield a length difference.

JavaCli Tooling

Code

snippet
public class NaturalSortOrder {

    public static void main(String[] args) {
        // compareTo 按码元逐位比较:'Z'(90) < 'a'(97),大写排在小写前面
        System.out.println("Z vs a:     " + "Zebra".compareTo("apple"));
        System.out.println("a vs b:     " + "apple".compareTo("banana"));

        // 前缀关系:较短串是较长串的前缀时,结果就是长度差
        System.out.println("app vs apple: " + "app".compareTo("apple"));

        // equalsIgnoreCase 为 true 的两个串,compareTo 仍可能非 0
        System.out.println("ignore case eq: " + "Apple".equalsIgnoreCase("apple"));
        System.out.println("compare:        " + "Apple".compareTo("apple"));
    }
}

Tracing what executes

The working surface is the class NaturalSortOrder and the function main — everything else is wiring.

Watch out for

  • No package entries exist here; the runtime itself supplies every capability used.

Applying it

Signature: public static void main(String[] args)

Output lines are prefixed (Z vs a:, a vs b:, app vs apple:), which keeps each printed line pointing back at the step behind it.

Interactive Tools for This Topic

FAQ

What does CompareTo Orders By Code Unit print when run?
No setup needed: run the file and look for labeled lines like `Z vs a:`, `a vs b:`, `app vs apple:` in the output.