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.
Code
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
CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.