Java String Methods: Indexing, Searching, Comparing and Transforming Text (OCP 21)
The String methods tested on the OCP Java 21 exam: length, charAt, code points, substring boundaries, indexOf with Java 21 range overloads, equals and compareTo, startsWith/contains, replace, strip versus trim, indent and stripIndent, isBlank, format and formatted, and method chaining.
kvi5hnuCode Sprout team member9 min readOn this page
String has more than 60 public methods. The exam focuses on about 30 of them, and expects you to know their exact behavior at the edges: what happens at the last index, what a method returns when nothing matches, and which methods throw. This article goes through them in groups. Keep article 16's rule in mind throughout: every method returns a new value and leaves the original string unchanged.
Length and single characters
var word = "kangaroo";
word.length(); // 8
word.charAt(0); // 'k'
word.charAt(7); // 'o'
word.charAt(8); // StringIndexOutOfBoundsException: Index 8 out of bounds for length 8
Indexes start at 0, but length() is an ordinary count. The last valid index is always length() - 1.
Code points. A char is a 16-bit UTF-16 unit. Characters outside the Basic Multilingual Plane, such as most emoji, take two chars (a surrogate pair). The code point methods work with whole Unicode characters:
| Method | Returns |
|---|---|
codePointAt(int index) | The Unicode code point starting at index, as an int |
codePointBefore(int index) | The code point that ends just before index |
codePointCount(int begin, int end) | How many code points lie in [begin, end) |
For plain ASCII text, codePointAt(i) is simply the numeric value of charAt(i), for example 97 for 'a'. With a typographic apostrophe in "We’re", codePointAt(2) is 8217. A string with one emoji between two letters has length() 4 but codePointCount(0, 4) 3.
substring: boundaries, not characters
String substring(int beginIndex)
String substring(int beginIndex, int endIndex)
The begin index is included and the end index is excluded. It helps to treat these numbers as the gaps between characters, which run from 0 to length():

word.substring(3); // "garoo"
word.substring(3, 5); // "ga" (length = 5 - 3)
word.substring(3, 8); // "garoo" (8 is a legal end: the boundary after the last char)
word.substring(8); // "" (an empty string, not an exception)
word.substring(3, 3); // ""
word.substring(4, 3); // StringIndexOutOfBoundsException (begin > end)
word.substring(3, 9); // StringIndexOutOfBoundsException (past the end)
substring is the method most often used in exam traps. Check three things every time: begin ≤ end, end ≤ length(), and the result has end - begin characters.
Searching
int indexOf(int ch) int indexOf(String str)
int indexOf(int ch, int fromIndex) int indexOf(String str, int fromIndex)
int indexOf(int ch, int beginIndex, int endIndex) int indexOf(String str, int beginIndex, int endIndex) // Java 21
int lastIndexOf(int ch) / lastIndexOf(String str) (plus fromIndex overloads)
- They return the index of the first match, or -1 if there's none. They never throw for a missing match.
- A
charargument goes to theint choverloads through widening. fromIndexis inclusive and is clamped rather than checked: a negative value means 0, and a value past the end simply finds nothing.- The three-argument overloads are new in Java 21. They search only
[beginIndex, endIndex), the same half-open range assubstring. UnlikefromIndex, these bounds are checked: invalid values throwStringIndexOutOfBoundsException.
word.indexOf('a'); // 1
word.indexOf("oo"); // 6
word.indexOf('a', 2); // 4 (starts looking at index 2)
word.lastIndexOf('a'); // 4
word.indexOf('z'); // -1
word.indexOf('o', 0, 6); // -1 (the o's are at 6 and 7, outside [0, 6))
word.indexOf("ar", 1, 6); // 4
The yes/no versions:
boolean startsWith(String prefix)
boolean startsWith(String prefix, int offset) // does the prefix appear at offset?
boolean endsWith(String suffix)
boolean contains(CharSequence s) // indexOf(s) != -1
They're all case-sensitive, and every string starts with, ends with and contains the empty string "".
Comparing
boolean equals(Object other) // same characters, same order, case-sensitive
boolean equalsIgnoreCase(String other)
int compareTo(String other) // from Comparable<String>
int compareToIgnoreCase(String other)
equalstakes anObject, so"6".equals(6)compiles and returnsfalse.equals(null)returnsfalse.compareToorders strings lexicographically by UTF-16 value. It returns a negative number, zero or a positive number. At the first position where the strings differ, it returns the difference of those two characters. If one string is a prefix of the other, it returns the difference in length. All uppercase ASCII letters (65–90) sort before all lowercase ones (97–122), so"B".compareTo("a")is negative, while"B".compareToIgnoreCase("a")is positive.
"apple".compareTo("apricot"); // -2 ('p' - 'r')
"ab".compareTo("abcd"); // -2 (length difference)
"B".compareTo("a"); // -31 (66 - 97)
On the exam, only the sign of the result matters. Article 19 covers == versus equals.
Transforming
| Method | Example | Result |
|---|---|---|
toUpperCase(), toLowerCase() | "Mixed 42!".toLowerCase() | "mixed 42!": non-letters unchanged |
replace(char, char) | "kangaroo".replace('o', '0') | "kangar00": every occurrence |
replace(CharSequence, CharSequence) | "aaaa".replace("aa", "b") | "bb": left to right, no overlaps |
repeat(int) (Java 11) | "ab".repeat(3) | "ababab". repeat(0) is "", negative values throw |
String.join(sep, parts…) | String.join("/", "x", "y") | "x/y" |
split(String regex) | "a,b,,c,,".split(",") | [a, b, , c]: trailing empty strings removed |
concat(String) | "a".concat("b") | "ab". A null argument throws |
replace is a literal search. replaceAll and replaceFirst take a regular expression, and split does too, so split(".") splits on every character. Escape it as split("\\.").
Whitespace
String strip() // removes leading and trailing whitespace (Unicode-aware, Java 11)
String stripLeading()
String stripTrailing()
String trim() // removes leading and trailing chars <= U+0020 (spaces, \t, \n, \r, controls)
boolean isEmpty() // length() == 0
boolean isBlank() // empty or only whitespace (Java 11)
strip() and trim() give the same result for ordinary spaces, tabs and newlines. They differ for Unicode spaces such as \u2000 (EN QUAD), which strip() removes and trim() keeps. Prefer the strip family in new code.
String text = " abc\t ";
text.trim().length(); // 3
text.strip().length(); // 3
text.stripLeading().length(); // 5 ("abc\t ")
text.stripTrailing().length(); // 4 (" abc")
" ".isEmpty(); // false
" ".isBlank(); // true
"".isBlank(); // true
Remember that \t and \n each count as one character.
Indentation: indent and stripIndent
These two methods came with text blocks (Java 12 and 15) and are notoriously tricky:
| Call | Changes indentation | Normalizes line breaks to \n | Adds a final \n if missing |
|---|---|---|---|
indent(n), n > 0 | Adds n spaces to every line | Yes | Yes |
indent(0) | No change | Yes | Yes |
indent(n), n < 0 | Removes up to n leading whitespace chars per line, as many as each line has | Yes | Yes |
stripIndent() | Removes the common (incidental) leading whitespace, like a text block does | Yes | No |
Work through this example carefully, counting characters:
String concat = " a\n" + " b\n" + " c"; // 9 chars: 4 spaces, 3 letters, 2 \n
concat.indent(2).length(); // 16 = 9 + 2×3 spaces + 1 added final \n
concat.indent(-1).length(); // 7 = 9 - 3 spaces + 1 final \n
concat.indent(-5).length(); // 6 = 9 - all 4 spaces + 1 final \n
concat.stripIndent().length(); // 6 = 9 - 1 common space per line, no \n added
The usual trap is the extra \n that indent always adds when the string doesn't already end with one.
Formatting
static String format(String format, Object... args)
static String format(Locale l, String format, Object... args)
String formatted(Object... args) // Java 15: "…".formatted(args)
| Specifier | Meaning |
|---|---|
%s | Any value, using String.valueOf (so null prints null) |
%d | Integer types: byte, short, int, long and their wrappers, BigInteger |
%f | Floating-point: float, double, BigDecimal. Six decimals by default |
%n | The platform line separator |
%b, %c, %x, %e | boolean (null → false), char, hex, scientific (good to recognize) |
Flags and widths go between % and the letter:
double pi = Math.PI;
"[%f]".formatted(pi); // [3.141593] six decimals, rounded
"[%.2f]".formatted(pi); // [3.14]
"[%8.3f]".formatted(pi); // [ 3.142] total width 8, padded on the left
"[%08.3f]".formatted(pi); // [0003.142] 0 flag pads with zeros
"[%-6s]".formatted("Joey"); // [Joey ] - flag left-justifies
"[%05d]".formatted(3); // [00003]
- Rounding is half-up:
"%.1f"turns 90.25 into90.3, and"%.0f"turns 2.5 into3. - The wrong type for a specifier throws at runtime, not compile time.
"%d".formatted(2.0)throwsIllegalFormatConversionException, and too few arguments throwsMissingFormatArgumentException. Extra arguments are silently ignored. %dwith acharalso throws.%saccepts anything.- Without a
Localeargument, the default locale decides the decimal separator (3,142in a German locale). PassLocale.ROOTorLocale.USwhen the output must be stable.
Method chaining
Because each String method returns a String, calls can be chained. Read from left to right, applying each method to the result of the previous one:
String result = " KanGaroo ".strip().toLowerCase().replace('a', 'A').substring(0, 4);
// "KanGaroo" → "kangaroo" → "kAngAroo" → "kAng"
Each step creates a new String. Unless the final result is assigned, the whole chain has no lasting effect.
What's current
- Java 21 added
indexOf(ch, beginIndex, endIndex)andsplitWithDelimiters. They're current and can appear on 1Z0-830. Stringgained no new methods in Java 22 through 25. Java 25 added a defaultgetCharsmethod toCharSequence, whichStringalready had.isBlank,strip,lines,repeat(Java 11),indent,transform(Java 12) andstripIndent,translateEscapes,formatted(Java 15) are all current.trimisn't deprecated, butstripis the Unicode-aware choice.
Exam traps from this article
A complete example
import java.util.Arrays;
import java.util.Locale;
public class Solution {
public static void main(String[] args) {
String word = "kangaroo";
System.out.println("-- length, charAt, substring --");
System.out.println(word.length() + " " + word.charAt(0) + " " + word.charAt(7));
System.out.println(word.substring(3) + " " + word.substring(3, 5) + " ["
+ word.substring(8) + "] [" + word.substring(3, 3) + "]");
try {
word.substring(4, 3);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("substring(4, 3): " + e.getMessage());
}
System.out.println("-- searching --");
System.out.println(word.indexOf('a') + " " + word.indexOf("oo") + " "
+ word.indexOf('a', 2) + " " + word.lastIndexOf('a') + " " + word.indexOf('z'));
System.out.println(word.indexOf('o', 0, 6) + " " + word.indexOf("ar", 1, 6)); // Java 21
System.out.println(word.startsWith("kan") + " " + word.startsWith("g", 3) + " "
+ word.endsWith("oo") + " " + word.contains("gar"));
System.out.println("-- comparing --");
System.out.println("Roo".equals("roo") + " " + "Roo".equalsIgnoreCase("roo") + " "
+ "roo".equals(null));
System.out.println("apple".compareTo("apricot") + " " + "ab".compareTo("abcd") + " "
+ "B".compareTo("a") + " " + "B".compareToIgnoreCase("a"));
System.out.println("-- transforming (each returns a new String) --");
System.out.println(word.toUpperCase() + " " + "Mixed 42!".toLowerCase());
System.out.println(word.replace('o', '0') + " " + "aaaa".replace("aa", "b"));
System.out.println("ab".repeat(3) + " " + String.join("/", "x", "y", "z"));
System.out.println(Arrays.toString("a,b,,c,,".split(",")));
System.out.println("-- whitespace --");
String padded = " \t joey \u2000\n";
System.out.println(padded.trim().length() + " " + padded.strip().length() + " "
+ padded.stripLeading().length() + " " + padded.stripTrailing().length());
System.out.println(" ".isEmpty() + " " + " ".isBlank() + " " + "".isBlank());
System.out.println("-- indentation --");
String concat = " a\n" + " b\n" + " c";
System.out.println(concat.length() + " " + concat.indent(2).length() + " "
+ concat.indent(-1).length() + " " + concat.indent(-5).length() + " "
+ concat.stripIndent().length());
System.out.print(concat.indent(-1).replace(' ', '.'));
System.out.println("-- formatting --");
String name = "Joey";
double weight = 2.456;
int age = 3;
System.out.println(String.format(Locale.ROOT, "%s weighs %.1f kg at %d", name, weight, age));
System.out.println("[%6s][%-6s][%05d][%8.3f][%b]".formatted(name, name, age, Math.PI, null));
try {
"%d kg".formatted(weight);
} catch (java.util.IllegalFormatConversionException e) {
System.out.println("%d with a double: " + e.getClass().getSimpleName());
}
System.out.println("-- chaining --");
String result = " KanGaroo ".strip().toLowerCase().replace('a', 'A').substring(0, 4);
System.out.println(result);
}
}
Output:
-- length, charAt, substring --
8 k o
garoo ga [] []
substring(4, 3): Range [4, 3) out of bounds for length 8
-- searching --
1 6 4 4 -1
-1 4
true true true true
-- comparing --
false true false
-2 -2 -31 1
-- transforming (each returns a new String) --
KANGAROO mixed 42!
kangar00 bb
ababab x/y/z
[a, b, , c]
-- whitespace --
6 4 7 7
false true true
-- indentation --
9 16 7 6 6
a
.b
c
-- formatting --
Joey weighs 2.5 kg at 3
[ Joey][Joey ][00003][ 3.142][false]
%d with a double: IllegalFormatConversionException
-- chaining --
kAng
Points to notice:
substring(8)on an 8-character string returns an empty string.substring(4, 3)throws with the messageRange [4, 3) out of bounds.indexOf('o', 0, 6)returns -1 because the ranged overload stops before index 6.compareTovalues are character differences ('p' - 'r','B' - 'a') or length differences.trim()leaves the Unicode space\u2000, so it returns 6 characters wherestrip()returns 4.indent(-1)removes one leading space per line and adds a final newline, as the dotted printout shows.formatteduses the default locale. The output shown is for an English-style locale, so the first format line passesLocale.ROOTto be safe.
Common questions
Why does indexOf take an int instead of a char?
So it can search for any Unicode code point, including characters that need two chars. Passing a char works through widening.
Is isEmpty() the same as length() == 0?
Yes. isBlank() is the one that also accepts whitespace-only strings.
format or formatted?
They do the same thing. formatted (Java 15) reads better in a chain or on a text block: """…""".formatted(x). Both throw on mismatched specifiers at runtime.
Should I use trim or strip?
Use strip. It follows Unicode's definition of whitespace. trim remains for compatibility and removes control characters that strip keeps.
Why does split drop some empty strings?
split(regex) calls split(regex, 0), which removes trailing empty strings. Leading and middle ones stay. Use split(regex, -1) to keep them all.
Summary
length()counts characters,charAt(i)is 0-based and throws past the end, and code point methods handle characters outside the BMP.substring(begin, end)includesbegin, excludesend, allowsend == length()and throws when begin > end or end > length.indexOf/lastIndexOfreturn -1 when there's no match. Java 21 added ranged overloads.startsWith,endsWithandcontainsare case-sensitive.equalsandequalsIgnoreCasetest equality.compareTogives a negative, zero or positive lexicographic order.replace, case conversion,repeat,join,splitand thestripfamily all return new strings.indent(n)changes indentation, normalizes line breaks and adds a final\n.stripIndent()removes common indentation without adding one.format/formattedwith%s %d %f %n, widths, precision and flags. Mismatched types fail at runtime.
Practice quiz
Test yourself with the String methods quiz: 10 exam-style questions with explanations.
Previous: Java Strings: Creation, Concatenation and Immutability (OCP 21)
Next: Java StringBuilder: Mutability, Chaining and Methods (OCP 21)
Related reading
- Java Strings: Creation, Concatenation and Immutability (OCP 21)
- Java break, continue, Labels, return and Unreachable Code (OCP 21)
- Java while, do/while, for and for-each Loops (OCP 21)
- Java Pattern Matching for switch: Type Patterns, when Guards, null and Record Patterns (OCP 21)
- Java switch Statements and switch Expressions: case Values, yield and Exhaustiveness (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.