Quick revision
The short answer
replace() swaps literal text everywhere, while replaceAll() treats its first argument as a regex and its replacement as a template where $ and backslash are special. contains(s) is simply indexOf(s) >= 0, and both are case-sensitive. equalsIgnoreCase() compares character by character with case folding, compareTo() orders by raw UTF-16 code units rather than language rules, substring(begin, end) excludes end and throws when out of range, and chars() streams UTF-16 code units while codePoints() streams whole Unicode characters.
What to remember
In this answer, we saw that replace treats its arguments as literal text while replaceAll uses a regex and a replacement template with special $ and backslash, that contains is indexOf >= 0 and both are case-sensitive, that equalsIgnoreCase folds case one character at a time while compareTo orders by UTF-16 code units and needs a Collator for people, that substring excludes its end index and throws when out of range, and that chars works in UTF-16 code units while codePoints gives whole characters.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
replace() swaps literal text everywhere, while replaceAll() treats its first argument as a regex and its replacement as a template where $ and backslash are special. contains(s) is simply indexOf(s) >= 0, and both are case-sensitive. equalsIgnoreCase() compares character by character with case folding, compareTo() orders by raw UTF-16 code units rather than language rules, substring(begin, end) excludes end and throws when out of range, and chars() streams UTF-16 code units while codePoints() streams whole Unicode characters.
Why this question is asked
These are methods we call every day, which is exactly why their small surprises cause so many bugs: a replaceAll that throws on a dollar sign, a name list sorted with all capital letters first, an emoji cut in half. Interviewers group them together to see whether we know what each method really does rather than what its name suggests. In this answer, we will take the pairs one at a time, show each with code and its output, explain the reason behind the behaviour, and note the bug each one tends to cause.
1Replace vs replaceAll: Literal Text Versus a Regex
Both methods replace every occurrence; the difference is how they read their arguments. replace(CharSequence target, CharSequence replacement) treats both as plain text. replaceAll(String regex, String replacement) compiles the first argument as a regular expression and reads the second as a replacement template, in which $1 means the text of group 1 and a backslash escapes the next character.
So the common bug is using replaceAll for literal text. It works until the text contains a regex character such as a dot, or the replacement contains a dollar sign, for example a price. The rule is simple: for literal text, use replace. If we really need a regex but the replacement comes from data, wrap it with Matcher.quoteReplacement(), and wrap a literal pattern with Pattern.quote().
2IndexOf vs contains
contains(s) is defined as indexOf(s) >= 0, so the two always agree. Both compare characters exactly, so they are case-sensitive, and both search with a straightforward scan that is O(n x m) in the worst case for a text of length n and a search string of length m. In practice the JVM uses fast intrinsic code for this, so it is rarely a bottleneck for normal strings.
Notice the fourth line. indexOf returns -1 when nothing is found and 0 when the match is at the start, so the test must be >= 0, or better, we call contains() when we only need a yes or no. For case-insensitive searches we lower-case both sides with Locale.ROOT, so a server's default locale cannot change the result.
3Equals, equalsIgnoreCase and compareTo
equals() checks that two strings have exactly the same characters; == only checks that they are the same object, which is why it must not be used for content. equalsIgnoreCase() walks both strings character by character and treats two characters as equal when they match after upper-casing or lower-casing. It is not locale-dependent, which makes it safe for keywords, but because it works one character at a time it cannot handle mappings that change length: the German sharp s becomes SS in upper case, so STRASSE.equalsIgnoreCase(strasse spelled with the sharp s) is false.
compareTo() returns a negative number, zero or a positive number, and that is all we should rely on. It compares the numeric values of UTF-16 code units, the 16-bit pieces a Java String is made of. That is fast and consistent, but it is not how people sort words.
Every capital letter has a smaller code than every lower-case letter, so natural order puts Zebra before apple, and accented letters such as e with an acute accent come after z. A Collator applies the rules of a language instead: it ignores case and accents first and uses them only to break ties.
4Substring(begin, end) and Its Boundaries
substring(begin, end) returns the characters from index begin up to but not including end, so the result has end minus begin characters. The excluded end makes slicing easy to chain: s.substring(0, k) and s.substring(k) split a string with nothing lost or repeated.
It throws StringIndexOutOfBoundsException when begin is negative, end is past the length, or begin is greater than end, so code that truncates user input must clamp first, for example with Math.min(end, s.length()). Since JDK 7 update 6 substring copies the characters into a new array. Before that, it shared the original array, and a short substring of a huge string kept the whole huge array alive in memory.
5Chars() vs codePoints()
A Java String is a sequence of UTF-16 code units, the 16-bit chars. Most characters fit in one char, but characters outside the Basic Multilingual Plane, such as most emoji, need two chars called a surrogate pair. length(), charAt() and chars() all work in chars, so they see such a character as two separate halves. codePoints() joins the pairs and returns each real character, a code point, once.
| Method | Reads its input as | Typical bug |
|---|---|---|
| replace | Literal text | None; the safe default |
replaceAll | Regex and replacement template | Dot or $ in data behaves specially |
indexOf / contains | Exact, case-sensitive text | Testing indexOf(...) > 0 |
equalsIgnoreCase | Char by char with case folding | Sharp s and other length changes |
compareTo | UTF-16 code unit values | Sorting names for people |
substring(b, e) | Half-open range [b, e) | Out-of-range end, cut surrogate pair |
chars / codePoints | Code units / code points | Counting emoji as two |
So any code that counts, truncates or reverses text a user can see should work with code points. Cutting at a char index can split a pair and produce invalid text. StringBuilder.reverse() already keeps pairs together, but a hand-written loop over chars does not.
6Follow-up questions
Why is compareTo not suitable for sorting names in a UI?
Because it orders by the numeric values of UTF-16 code units, not by any language's rules. All upper-case letters come before all lower-case ones, so Zebra sorts before apple, and accented letters land after z, so a name starting with an accented E appears at the end of the list. Languages also disagree: in Swedish, a with a ring sorts after z, while in German a with an umlaut sorts with a. For user-visible lists we use java.text.Collator for the user's Locale, or ICU4J for more control, and we cache the Collator or its CollationKeys when sorting large lists.
Does replace() only replace the first occurrence?
No, this is a common misunderstanding caused by the name replaceAll. replace() replaces every occurrence of the literal text, and replaceAll() replaces every match of a regex. The method that replaces only one occurrence is replaceFirst(), and it also takes a regex. So the choice between replace and replaceAll is about literal versus regex, not about one versus all.
Is String.CASE_INSENSITIVE_ORDER a good comparator for names?
It is better than compareTo for machine-facing ordering, because it ignores case the same way as compareToIgnoreCase, but it still compares code units, so accents and language rules are ignored. It is fine for sorting keys, file names or identifiers in a stable, locale-independent way. For names shown to people we still use a Collator.
7Conclusion
In this answer, we saw that replace treats its arguments as literal text while replaceAll uses a regex and a replacement template with special $ and backslash, that contains is indexOf >= 0 and both are case-sensitive, that equalsIgnoreCase folds case one character at a time while compareTo orders by UTF-16 code units and needs a Collator for people, that substring excludes its end index and throws when out of range, and that chars works in UTF-16 code units while codePoints gives whole characters.
Open with
These pairs look similar but read their inputs differently. replace takes literal text and replaces every occurrence, while replaceAll takes a regex and a replacement template, so a dot matches any character and a dollar sign in the replacement means a group reference; I use replace for literal text, or Matcher.quoteReplacement and Pattern.quote if I really need a regex. contains is just indexOf greater than or equal to zero, both case-sensitive, and the typical bug is testing indexOf greater than zero, which misses a match at the start. equals compares content, equalsIgnoreCase compares character by character with case folding, which is locale-independent but cannot handle things like the German sharp s, and compareTo orders by UTF-16 code unit values, so capitals come before lower case and accented letters after z; for anything a user sees, I sort with a Collator for their locale. substring with begin and end excludes the end, so the length is end minus begin, it throws StringIndexOutOfBoundsException when out of range, and since Java 7 it copies the characters.
Then, if they want more
Finally, a String is UTF-16, so chars streams code units and splits an emoji into two surrogate halves, while codePoints streams whole characters; I use code points whenever I count, truncate or reverse user-visible text.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 7
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Explain the difference between these String methods and the common bugs with each...": https://scrivio-interview-library.netlify.app/java/strings/8cfcb488fb/