Lesson · Strings & Text
The String API: the methods that matter and their traps
12 min readString API
length, charAt, substring, indexOf, replace, split, strip: the working surface of String, each with the boundary or semantics quirk that bites.
Reading and slicing
length() counts units, charAt(i) reads one code unit (surrogates from the encoding topic apply), isEmpty() and isBlank() distinguish empty from whitespace-only, one of those small methods that removes a dozen hand-written checks. substring(begin, end) is half-open: begin inclusive, end exclusive, so substring(5, 5) is empty and substring(0, s.length()) is the whole string.
indexOf and lastIndexOf return -1 on missing, and the two-argument forms search from a start index. contains, startsWith, endsWith are the readable wrappers over indexOf comparisons, and they are what most code should call directly. All index-taking methods throw StringIndexOutOfBoundsException for out-of-range values, including substring(s.length() + 1).
Transforming: case, trim, replace
toUpperCase and toLowerCase are locale-sensitive and famously so for Turkish (dotted and dotless i: "I".toLowerCase() is "ı" there). Pass Locale.ROOT for protocol strings, default locale for display text. trim removes characters ≤ U+0020; strip (Java 11) removes Unicode whitespace, which is the correct one for international input.
replace(CharSequence, CharSequence) replaces all literal occurrences; replace(char, char) is the fast primitive variant. replaceAll and replaceFirst take regexes, and that distinction is the classic trap: replace(".", "-") changes dots, replaceAll(".", "-") matches every character because dot is the regex wildcard. The name not following the semantics is exactly the kind of standard-library nuisance worth memorising once.
split and its regex
split(regex) also takes a regex, so "a.b".split(".") splits into nothing: the dot matches everything. split(Pattern.quote(".")) or split("\\.") is what was meant. The limit argument matters too: split(regex, 0) (the default) drops trailing empty strings, while a negative limit keeps them, so splitting "a,b,," gives two or three trailing empties depending on the argument.
For simple single-character or literal separators, prefer a hand-written loop or StringTokenizer-style splitting without regex when it is hot; split compiles a Pattern on every call, which matters in loops. The correctness trap is bigger than the performance one: know the argument is a regex, always.
Comparison and joining
equals versus equalsIgnoreCase, compareTo for the natural order (lexicographic by code unit), compareToIgnoreCase for case-insensitive: the case-insensitive pair uses toLowerCase internally, so locale edge cases apply here too. matches(regex) is full-string matching, not find: "abc".matches("b") is false because the whole string must match the pattern.
join(delimiter, elements) assembles strings from a collection with the delimiter between (and only between): String.join(", ", names). It is the readable inverse of split, and it removes the trailing-delimiter bug that hand-built loops always produce. String.format joins in a different sense and belongs to the formatting topic that follows.
substring is half-open; split takes a regex
Two facts cover most String API bugs in review. substring(begin, end) excludes end, so lengths are end minus begin and off-by-one thinking is the same as loops. split and replaceAll take regexes: quote literals with Pattern.quote or escape them, or a dot will match the world.
Interview angles
replace versus replaceAll?+
Despite the names, replace takes literal CharSequences; replaceAll takes a regex. replaceAll(".", "-") replaces every character because dot is a wildcard. When the second argument of replaceAll contains $ or backslashes it is also treated specially (Matcher.quoteReplacement).
Why does split sometimes drop trailing empty strings?+
The default limit 0 discards trailing empties; a negative limit keeps them. "a,b,,".split(",") gives [a, b], with -1 gives [a, b, , ]. The behaviour is the specified inheritance from Pattern.split.
trim versus strip?+
trim removes characters up to U+0020 (historical, byte-oriented). strip (Java 11) removes Unicode whitespace via Character.isWhitespace. For anything international, strip is the correct choice, and stripTrailing or stripLeading when only one side is meant.