Java Zero to All All questionsPractise free
Interview questions › Practice Programs — Master Every Pattern › Strings — Practice Programs

What does String.compareTo return, and how does it order strings?

Level I · BeginnerStrings — Practice Programs
Short answer

compareTo does a lexicographic (dictionary) comparison character by character using Unicode values.

Explanation

It returns a negative int if this string sorts before the argument, zero if equal, and positive if after. If one is a prefix of the other, the shorter sorts first and the return value is the length difference. This is the natural ordering used by Collections.sort, TreeSet, and TreeMap; a Comparator lets you define a different ordering (e.g. by length, or case-insensitive).

Common mistakes
  • Saying compareTo returns only -1, 0 or 1.
  • Forgetting it is case-sensitive.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Strings — Practice Programs.

Practise free

More on Strings — Practice Programs