The Java String API, Code Points, StringBuilder and Text Blocks
A working tour of the String API (strip, startsWith, replace, indexOf ranges, formatted, lines, isBlank and more), how to read the Javadoc, iterating over code points correctly, building strings fast with StringBuilder, and writing multi-line text with text blocks.
kvi5hnuCode Sprout team member15 min readOn this page
The previous article covered the core ideas of strings: concatenation, substrings, immutability and equality. The String class has around 100 methods, though, and the standard library has thousands of classes. This article covers:
- The
Stringmethods you'll use every day, including modern ones added in Java 11–21. - How to read the official API documentation, so you can find anything else yourself.
- Code points: how to process text correctly when it contains emojis and other characters outside the Basic Multilingual Plane.
StringBuilder: building strings efficiently from many pieces.- Text blocks: multi-line string literals.
The Most Useful String Methods
In the tables below, the number after a method is the Java version that introduced it (methods without a number have existed since Java 1.0 or 1.4). All of these methods return new strings or values. None of them change the original string.
Inspecting
| Method | What it does |
|---|---|
int length() | number of char code units |
char charAt(int index) | the code unit at index. Low level: rarely what you want for non-ASCII text |
boolean isEmpty() 6 | length() == 0 |
boolean isBlank() 11 | empty or only whitespace |
boolean startsWith(String prefix) / endsWith(String suffix) | tests the beginning or end |
boolean contains(CharSequence s) 5 | s occurs somewhere in the string |
boolean equals(Object other) / equalsIgnoreCase(String other) | content equality |
int compareTo(String other) / compareToIgnoreCase | dictionary order: negative, 0 or positive |
Searching
| Method | What it does |
|---|---|
int indexOf(String str) | first occurrence, or -1 |
int indexOf(String str, int from) | first occurrence at or after from |
int indexOf(String str, int from, int to) 21 | first occurrence within the range from … to - 1 |
int lastIndexOf(String str) / lastIndexOf(String str, int from) | last occurrence, searching backwards |
indexOf and lastIndexOf also have versions that take a single character (as an int code point), such as s.indexOf('@').
Producing new strings
| Method | What it does |
|---|---|
substring(int begin) / substring(int begin, int end) | part of the string (end exclusive) |
toLowerCase() / toUpperCase() | case conversion |
strip() 11, stripLeading() 11, stripTrailing() 11 | remove whitespace at both ends, the start, or the end |
trim() | old version of strip; only removes characters ≤ U+0020 |
replace(CharSequence old, CharSequence new) | replaces every occurrence of plain text |
replace(char old, char new) | replaces every occurrence of a character |
replaceAll(String regex, String repl) / replaceFirst | replace by regular expression |
String.join(CharSequence delim, CharSequence... parts) 8 | joins with a separator |
repeat(int count) 11 | repeats the string |
split(String regex) 1.4 | breaks into an array, dropping trailing empty strings |
splitWithDelimiters(String regex, int limit) 21 | like split, but keeps the delimiters as separate elements |
formatted(Object... args) 15 | printf-style formatting: "%d items".formatted(n) |
String.valueOf(x) | converts any value (int, double, boolean, object…) to a string |
indent(int n) 12 | adds (or removes, if negative) n spaces at the start of each line |
lines() 11 | a stream of the lines in the string |
transform(Function f) 12 | applies a function: s.transform(f) is f.apply(s), handy in method chains |
stripIndent() 15 / translateEscapes() 15 | text-block helpers, explained below |
Here are many of them in action:
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
String s = " Hello, World! ";
System.out.println("[" + s.strip() + "]");
System.out.println("[" + s.stripLeading() + "]");
System.out.println("[" + s.stripTrailing() + "]");
String file = "Report.PDF";
System.out.println(file.startsWith("Rep") + " " + file.toLowerCase().endsWith(".pdf"));
System.out.println(file.contains("port"));
System.out.println("banana".replace("a", "o"));
System.out.println("2024-05-17".replace('-', '/'));
System.out.println("a1b22c333".replaceAll("[0-9]+", "#"));
String text = "one two one two";
System.out.println(text.indexOf("one", 1) + " " + text.indexOf("two", 0, 5));
System.out.println("Hi %s, you are %d".formatted("Ada", 36));
System.out.println("line1\nline2\nline3".lines().count());
System.out.println("hello".transform(t -> t + "!").toUpperCase());
System.out.println(Arrays.toString("a1b2c3".splitWithDelimiters("\\d", 0)));
System.out.println("ß".toUpperCase() + " " + "TITLE".toLowerCase());
System.out.println(String.valueOf(42) + String.valueOf(true) + String.valueOf(3.5));
System.out.println("\u2003x\u2003".trim().length() + " " + "\u2003x\u2003".strip().length());
System.out.print("ab\ncd".indent(2));
}
}
[Hello, World!]
[Hello, World! ]
[ Hello, World!]
true true
true
bonono
2024/05/17
a#b#c#
8 -1
Hi Ada, you are 36
3
HELLO!
[a, 1, b, 2, c, 3]
SS title
42true3.5
3 1
ab
cd
Some details worth noticing:
text.indexOf("two", 0, 5)is -1."two"starts at index 4, but the match would extend past index 5, the end of the search range.replacereplaces all occurrences, despite its name. It treats its arguments as plain text, whilereplaceAlltakes a regular expression.- Case conversion can change the length: the German
"ß"becomes"SS"in uppercase. trim()doesn't recognise the Unicode "em space" (U+2003), butstrip()does. Preferstripin new code.transformtakes a lambda expression (t -> t + "!"). Lambdas get a full article in the interfaces part. For now, read it as "taketand producet + "!"".
Reading the Online API Documentation
No one memorises every class and method. Professional Java developers keep the API documentation (Javadoc) open and look things up all the time. Learning to read it is one of the most valuable skills in this course.
- Where:
https://docs.oracle.com/en/java/javase/25/docs/api/for Java 25 (replace25with your version). You can also download the docs as a zip from the JDK download page and browse them offline. - Search: the search box at the top finds classes, methods and topics. Type
Stringand pickjava.lang.String. - Class page structure:
- The class description at the top explains its purpose, often with examples.
- The Method Summary table lists every method with a one-line description. Tabs filter static, instance, concrete and deprecated methods.
- Method Details give the full description of each method: parameters, return value, exceptions it throws, and the version that added it (the "Since:" line).
- Module and package: at the top of the page you'll see
Module java.base, Package java.lang. Classes injava.lang(such asString,Math,System) can be used without animport. Packages and imports are covered in the objects and classes part.
Code Points: Processing Text Correctly
As explained in the article on char and Unicode, a Java String is a sequence of UTF-16 code units (char values). Most characters take one code unit, but characters with code points above U+FFFF (most emojis, many historic scripts, rare CJK ideographs, mathematical letters) take two: a surrogate pair.

| Method | Meaning |
|---|---|
s.length() | number of code units |
s.codePointCount(start, end) | number of code points between two indexes |
s.codePointAt(i) | the code point that starts at index i |
Character.charCount(cp) | 1 or 2: how many code units the code point needs |
s.offsetByCodePoints(start, n) | the index that is n code points after start |
s.codePoints() | a stream of all code points; .toArray() gives an int[] |
new String(codePoints, offset, count) | builds a string from an array of code points |
Character.toString(cp) 11 | a string containing one code point |
To walk through a string code point by code point, advance the index by Character.charCount:
public class Solution {
public static void main(String[] args) {
String s = "I💛Java";
System.out.println(s.length() + " " + s.codePointCount(0, s.length()));
System.out.println((int) s.charAt(1) + " " + (int) s.charAt(2));
System.out.println(s.codePointAt(1) + " " + Character.charCount(s.codePointAt(1)));
int i = 0;
while (i < s.length()) {
int cp = s.codePointAt(i);
System.out.print(Character.toString(cp) + "(" + cp + ") ");
i += Character.charCount(cp);
}
System.out.println();
int[] cps = s.codePoints().toArray();
System.out.println(cps.length + " " + new String(cps, 0, cps.length));
int idx = s.offsetByCodePoints(0, 2);
System.out.println(idx + " " + s.substring(idx));
}
}
7 6
55357 56475
128155 2
I(73) 💛(128155) J(74) a(97) v(118) a(97)
6 I💛Java
3 Java
Calling charAt(1) gives 55357, half of the emoji (a high surrogate). Code that loops with charAt and handles each char as a character will mangle such text. Using codePoints() is usually the simplest correct choice.
To move backwards, use s.codePointBefore(i), or check Character.isSurrogate(s.charAt(i)) and step back one more position.
Building Strings: StringBuilder
Every concatenation with + creates a new String and copies all the characters into it. Inside a loop, this gets slow: building a string from n pieces copies roughly n²/2 characters in total.

A StringBuilder holds a growable, mutable buffer of characters. You add to it as many times as you like, and turn it into a String once at the end:
StringBuilder builder = new StringBuilder(); // empty
StringBuilder invoice = new StringBuilder("INVOICE\n"); // with initial content
builder.append(str); // appends a string (or any value)
builder.appendCodePoint(cp); // appends one code point (1 or 2 chars)
String result = builder.toString();
append is overloaded for all types (int, double, char, boolean, objects), and each StringBuilder method returns the builder itself, so calls can be chained: new StringBuilder().append("x = ").append(42).toString().
public class Solution {
public static void main(String[] args) {
StringBuilder b = new StringBuilder();
for (int i = 1; i <= 5; i++) {
if (i > 1) b.append(", ");
b.append(i * i);
}
System.out.println(b + " len=" + b.length());
b.insert(0, "Squares: ").append('.');
System.out.println(b);
b.delete(0, 9);
System.out.println(b);
System.out.println(new StringBuilder("stressed").reverse());
System.out.println(new StringBuilder().repeat("ab", 3).repeat('-', 4));
final int REGIONAL_INDICATOR_A = 127462;
String country = "IT";
String flag = new StringBuilder()
.appendCodePoint(country.charAt(0) - 'A' + REGIONAL_INDICATOR_A)
.appendCodePoint(country.charAt(1) - 'A' + REGIONAL_INDICATOR_A)
.toString();
System.out.println(flag + " " + flag.length() + " " + flag.codePointCount(0, flag.length()));
StringBuilder x = new StringBuilder("hello");
x.setCharAt(0, 'J');
x.replace(1, 5, "ava");
System.out.println(x + " " + x.indexOf("v") + " " + x.charAt(1));
x.setLength(0);
System.out.println("[" + x + "]");
}
}
1, 4, 9, 16, 25 len=15
Squares: 1, 4, 9, 16, 25.
1, 4, 9, 16, 25.
desserts
ababab----
🇮🇹 4 2
Java 2 a
[]
The flag example shows appendCodePoint at work. Flag emojis are pairs of regional indicator symbols, code points 127462 (🇦, letter A) to 127487 (🇿, letter Z). The country code "IT" maps to two regional indicators, which systems display as the Italian flag. The result is 2 code points, but 4 chars.
StringBuilder methods
| Method | What it does |
|---|---|
StringBuilder() / StringBuilder(CharSequence initial) / StringBuilder(int capacity) | constructors |
int length() | current number of code units |
append(x) | appends any value; returns the builder |
appendCodePoint(int cp) | appends a code point as 1 or 2 code units |
insert(int offset, x) | inserts at a position |
delete(int start, int end) / deleteCharAt(int i) | removes code units start … end - 1, or one |
replace(int start, int end, String s) | replaces a range |
setCharAt(int i, char c) / charAt(int i) | changes or reads one code unit |
indexOf(String s) | searches, like String.indexOf |
reverse() | reverses the code points (surrogate pairs stay intact) |
repeat(CharSequence cs, int count) 21 / repeat(int codePoint, int count) 21 | appends repeated copies |
setLength(int n) | truncates (or pads with '\0'); setLength(0) clears it for reuse |
toString() | creates a String with the current contents |
When to use it, and StringBuffer
- Use
StringBuilderwhen you build a string in a loop or from many pieces. - Plain
+is fine for a fixed expression such as"Hello, " + name + "!". The compiler already optimises it (since Java 9 usinginvokedynamic/StringConcatFactory), and it's more readable.String.join,repeatand the stream methodCollectors.joiningare also good options. StringBufferis the original (Java 1.0) version of the same API. All its methods are synchronized, which makes it slightly slower; it's only needed if several threads modify the same buffer, which is almost never a good design. UseStringBuilder(Java 5) in new code. You'll still seeStringBufferin old code and some older APIs.
Text Blocks
Before Java 15, multi-line text in source code meant gluing lines together with \n and +:
String html = "<div class=\"warning\">\n" +
" Beware of \"quotes\"\n" +
"</div>\n";
A text block (Java 15) starts with """ followed by a line break, and ends with """:
String html = """
<div class="warning">
Beware of "quotes"
</div>
""";
Both produce exactly the same string. The text block is easier to read, and you can paste HTML, JSON, SQL or other languages in directly. A text block is just another way to write a String literal: the result is an ordinary String.
The rules
- The opening
"""must be followed by a line break. That first line break isn't part of the string. - The last line: if the closing
"""is on its own line, the string ends with a newline. To end without one, put"""right after the last character:Please enter your name:""";. - Quotes don't need escaping, except when the content ends with
"right before the closing""", or contains three or more quotes in a row (escape one of them:\"""). - Backslashes still need escaping (
\\), and all the usual escapes (\n,\t,\",\u…) work. - Line endings are normalised to
\n, even if the source file uses Windows\r\n. - Trailing spaces on each line are removed. To keep one, end the line with
\s(an escaped space). It's useful for prompts:Please enter your name:\s. - A
\at the end of a line joins it with the next line, so no newline is inserted. Use it for long lines you want to wrap in source code.
Indentation stripping
Text blocks are usually indented to line up with the surrounding code. The compiler removes the common indentation: the smallest amount of leading whitespace shared by all non-blank lines, including the line with the closing """.

- Extra indentation beyond the common amount is kept (the three spaces before
Beware). - Entirely blank lines don't count when finding the common indentation.
- The closing
"""line counts. Moving it further left keeps more indentation in the result. Putting the closing"""at the very left margin keeps all indentation. - Java doesn't assume a width for tab characters. The whitespace must match exactly across lines, so don't mix tabs and spaces in text blocks.
public class Solution {
public static void main(String[] args) {
String greeting = """
Hello
World
""";
System.out.println(greeting.equals("Hello\nWorld\n"));
String prompt = """
Hello, my name is Hal. \
Please enter your name:\s""";
System.out.println("[" + prompt + "]");
String html = """
<div class="warning">
Beware of "quotes"
</div>
""";
System.out.print(html);
String left = """
indented
""";
System.out.print("[" + left + "]");
System.out.println();
String q = """
She said \"""yes\""" and \\ is a backslash""";
System.out.println(q);
String json = """
{"name": "%s", "age": %d}""".formatted("Ada", 36);
System.out.println(json);
}
}
true
[Hello, my name is Hal. Please enter your name: ]
<div class="warning">
Beware of "quotes"
</div>
[ indented
]
She said """yes""" and \ is a backslash
{"name": "Ada", "age": 36}
In the left example, the closing """ is indented two spaces less than the content, so two spaces of indentation remain.
Common questions
Should I use + or StringBuilder for a few concatenations?
Use + for a single expression. Since Java 9 the compiler turns it into an efficient invokedynamic call that sizes the result exactly. Use StringBuilder when you append inside a loop or across several statements.
What is the difference between strip() and trim()?
trim() removes characters with codes up to U+0020 (space and ASCII control characters). strip() (Java 11) removes all Unicode whitespace, including the em space and other wide spaces. Use strip, stripLeading and stripTrailing in new code.
How do I check whether a string contains only digits?
For ASCII digits, use s.matches("\\d+") or s.chars().allMatch(c -> c >= '0' && c <= '9') (which also accepts an empty string). Character.isDigit accepts digits from other scripts too, such as Arabic-Indic digits, which Integer.parseInt also accepts. To find out whether a string is a valid number, it is usually simplest to parse it and catch NumberFormatException.
Can a text block contain """?
Yes, if you escape at least one of the quotes: \""". Single and double quotes need no escaping in a text block. A quote immediately before the closing delimiter must also be escaped, or you can move the closing """ to the next line.
Will string templates come back?
They were withdrawn in Java 23. A redesigned version may return in the future, but no release up to Java 27 contains one. Use formatted, String.format, MessageFormat or concatenation until then, and use PreparedStatement parameters for SQL.
Summary
Stringhas about 100 methods; the most useful includestrip,startsWith/endsWith,contains,indexOf(with a range since Java 21),replace/replaceAll,toUpperCase/toLowerCase,join,repeat,split,formatted,linesandisBlank. They all return new values.- Prefer
strip()totrim(), and useLocale.ROOTfor case conversion of machine-readable text. - The Javadoc is your reference. Learn to use the search box, method summary and the "Since:" line.
length()counts code units, not characters. Iterate withcodePointAt+Character.charCount, or withcodePoints(), to handle emojis and other supplementary characters correctly.- Use
StringBuilder(append,insert,delete,reverse,repeat,toString) to build strings in loops.StringBufferis its legacy synchronized twin. - Text blocks (
"""…""") write multi-line strings: common indentation is stripped, trailing spaces are removed (use\sto keep one),\at a line end joins lines, and quotes rarely need escaping.
Practice Questions
What is the result of " Java ".strip().toLowerCase().replace("a", "4")?
"j4v4". Each call returns a new string, and the next call operates on it.
Why might countVowels using s.charAt(i) give wrong results for a string containing "𝔸" (U+1D538)?
U+1D538 is outside the BMP, so it takes two chars (a surrogate pair). Looping with charAt sees two meaningless halves instead of one character. Use s.codePoints() or step through with codePointAt and Character.charCount.
Rewrite this loop so it doesn't create a new String on every iteration: String r = ""; for (int i = 0; i < 1000; i++) r += i + ",";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.append(i).append(',');
String r = sb.toString();
A text block has the lines " a", " b" and a closing """ indented 4 spaces. What string does it produce?
String s = """
a
b
""";
It produces "a\n b\n". The common indentation (4 spaces, including the closing line) is removed; b keeps its 2 extra spaces, and there's a final newline because the closing """ is on its own line.
How do you write a text block that ends with "Name: " (with a trailing space) and no final newline?
String prompt = """
Name:\s""";
The closing """ directly follows the last character, so there's no final newline, and \s keeps the trailing space that would otherwise be stripped.
A method uses StringBuffer for a local variable inside one method. Should you change it?
Yes, you can safely switch to StringBuilder. The variable is local, so only one thread can use it, and the synchronization in StringBuffer only costs time. The API is identical.
Previous: Java Strings: Concatenation, Substrings, Immutability and Comparing with equals
Next: Java Console Input and Output: Scanner, Console and printf Formatting
Related reading
- Java Switch Expressions: Arrow Labels, Multiple Labels, yield and case null
- Java Variables, Constants, var and final Explained
- Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
- Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.