String Utility Methods
Java 11 and later versions added small String methods that replace helpers many projects used to write or import: repeat, isBlank, strip, lines, indent, transform, formatted and more. This page lists them by version, runs each with its edge cases, then gives recipes for tasks that still have no built-in method and patterns for handling null.
Contents
How the String API has grown
For most of Java's history, the StringStringUtilsnull
| Method | Since | Replaces |
|---|---|---|
String.joinchars() | Java 8 | Join loops; index loops over chars |
repeat(n) | Java 11 | Loops that append the same text |
isBlank() | Java 11 | trim().isEmpty() |
strip()stripLeading()stripTrailing() | Java 11 | trim() |
lines() | Java 11 | split("\\R") |
indent(n)transform(f) | Java 12 | Indentation helpers; temporary variables |
formatted(args)stripIndent()translateEscapes() | Java 15 | String.format |
indexOf(ch, begin, end)splitWithDelimiters | Java 21 | substring |
StringBuilder.repeat | Java 21 | Padding loops on builders |
The programs were compiled and run on JDK 21, which the Java 21 methods need. Several methods have their own detailed pages, linked below.
Java 11: repeat, isBlank, strip and lines
Java 11 added the most commonly used helpers. The inputs include the edge cases: zero and negative counts, an em space, and text that ends with a line terminator or consists only of them.
import java.util.List;
public class Java11Methods {
public static void main(String[] args) {
// repeat
System.out.println("\"ab\".repeat(3) = " + "ab".repeat(3));
System.out.println("\"-\".repeat(10) = " + "-".repeat(10));
System.out.println("\"ab\".repeat(0) = [" + "ab".repeat(0) + "]");
try {
"ab".repeat(-1);
} catch (IllegalArgumentException e) {
System.out.println("\"ab\".repeat(-1) -> " + e.getMessage());
}
// isBlank vs isEmpty
for (String s : new String[] {"", " \t\n", "\u2003", " x "}) {
System.out.printf("%-10s isEmpty=%-5b isBlank=%b%n",
visible(s), s.isEmpty(), s.isBlank());
}
// strip, stripLeading, stripTrailing
String padded = " padded ";
System.out.println("strip: [" + padded.strip() + "] leading: [" + padded.stripLeading()
+ "] trailing: [" + padded.stripTrailing() + "]");
// lines: splits on \n, \r\n and \r; no empty line after a final terminator
List<String> lines = "first\nsecond\r\nthird\rfourth\n".lines().toList();
System.out.println("lines: " + lines + " (" + lines.size() + " lines)");
System.out.println("\"\".lines().count() = " + "".lines().count()
+ ", \"\\n\".lines().count() = " + "\n".lines().count()
+ ", \"\\n\\n\".lines().count() = " + "\n\n".lines().count());
// Character.toString(int): a code point to a String
System.out.println("Character.toString(0x1D11E).length() = "
+ Character.toString(0x1D11E).length());
}
static String visible(String s) {
return "\"" + s.replace("\t",
"\\t").replace("\n", "\\n").replace("\u2003", "\\u2003") + "\"";
}
}
Output:
"ab".repeat(3) = ababab
"-".repeat(10) = ----------
"ab".repeat(0) = []
"ab".repeat(-1) -> count is negative: -1
"" isEmpty=true isBlank=true
" \t\n" isEmpty=false isBlank=true
"\u2003" isEmpty=false isBlank=true
" x " isEmpty=false isBlank=false
strip: [padded] leading: [padded ] trailing: [ padded]
lines: [first, second, third, fourth] (4 lines)
"".lines().count() = 0, "\n".lines().count() = 1, "\n\n".lines().count() = 2
Character.toString(0x1D11E).length() = 2
returns the empty string and a negative count throwsrepeat(0) with "count is negative: -1".IllegalArgumentException is true for the empty string, for whitespace-only text and for the em space U+2003, because it usesisBlank() . It is false forCharacter.isWhitespace . More about which characters count is on the" x "whitespace page . removes whitespace from both ends, and the leading and trailing variants from one end only.strip recognizeslines() ,\n and a lone\r\n , so the mixed text gave 4 lines. A final terminator does not create an empty last line, the empty string has 0 lines, and\r has 2 empty lines."\n\n" , also new in Java 11, turns a code point into a string; the G clef needs 2 chars.Character.toString(int)
Java 12 to 21: indent, transform, formatted and more
The later additions are mostly about multi-line text and fluent code. Each input is small enough to check by eye, and one shows a method rejecting input it does not support.
import java.util.Arrays;
public class LaterMethods {
public static void main(String[] args) {
// Java 12: indent adds or removes leading spaces on every line, and ends with \n
String block = "line one\n line two";
System.out.print("indent(4):\n" + block.indent(4));
System.out.print("indent(-2):\n" + " a\n b\nc".indent(-2));
System.out.println("indent(0) of \"a\\r\\nb\" = "
+ "a\r\nb".indent(0).replace("\n", "\\n"));
// Java 12: transform applies any function, keeping a left-to-right chain
int n = " 42 ".transform(String::strip).transform(Integer::parseInt);
System.out.println("transform: " + (n + 1));
// Java 15: formatted, stripIndent, translateEscapes
String json = """
{"name": "%s", "age": %d}""".formatted("Ada", 36);
System.out.println("formatted: " + json);
System.out.println("stripIndent: ["
+ " a\n b".stripIndent().replace("\n", "|") + "]");
String escaped = "tab\\there\\nnext \\101";
System.out.println("translateEscapes: [" + escaped.translateEscapes().replace("\n", "|")
+ "]");
try {
"\\u0041".translateEscapes();
} catch (IllegalArgumentException e) {
System.out.println("translateEscapes on \\u0041: " + e.getMessage());
}
// Java 21: indexOf with a range, splitWithDelimiters
System.out.println("\"banana\".indexOf('a', 2, 4) = " + "banana".indexOf('a', 2, 4));
System.out.println("splitWithDelimiters: "
+ Arrays.toString("a1b22c".splitWithDelimiters("\\d+", 0)));
// Java 21: StringBuilder.repeat
StringBuilder sb = new StringBuilder("x");
sb.repeat("yz", 2).repeat('!', 3);
System.out.println("StringBuilder.repeat: " + sb);
}
}
Output:
indent(4):
line one
line two
indent(-2):
a
b
c
indent(0) of "a\r\nb" = a\nb\n
transform: 43
formatted: {"name": "Ada", "age": 36}
stripIndent: [a| b]
translateEscapes: [tab here|next A]
translateEscapes on \u0041: Invalid escape sequence: \u \\u0075
"banana".indexOf('a', 2, 4) = 3
splitWithDelimiters: [a, 1, b, 22, c]
StringBuilder.repeat: xyzyz!!!
adds four spaces to each line, keeping relative indentation.indent(4) removes up to two leading spaces per line, never more than a line has, soindent(-2) was unchanged.c always ends the result withindent and normalizes\n to\r\n , even with\n .indent(0) applies a function and returns its result, which need not be a string. Here it strips and then parses, reading left to right instead of nesting calls.transform isformatted with the template as the receiver, convenient after a text block; see theString.formatformatting page . removes the indentation common to all lines, as the compiler does for text blocks.stripIndent interprets escape sequences such astranslateEscapes ,\t and the octal\n (the letter\101 ) in text read at run time, but rejectsA , because Unicode escapes are handled by the compiler before strings exist.\u- Java 21's
searches only indexes 2 and 3 and found theindexOf('a', 2, 4) at 3.a keeps the separators as elements; see thesplitWithDelimiterssplit page . appends a string or a character a number of times and returns the builder, so it chains.StringBuilder.repeat
Recipes for tasks with no built-in method
Some everyday operations still have no method on String
import java.util.Locale;
public class Recipes {
// First letter upper case, by code point, null and empty safe
static String capitalize(String s) {
if (s == null || s.isEmpty()) {
return s;
}
int first = s.codePointAt(0);
return new StringBuilder().appendCodePoint(Character.toTitleCase(first))
.append(s, Character.charCount(first), s.length()).toString();
}
// Letters only, any script, compared case-insensitively
static boolean isPalindrome(String s) {
String letters = s.replaceAll("[^\\p{L}\\p{N}]", "").toLowerCase(Locale.ROOT);
return new StringBuilder(letters).reverse().toString().equals(letters);
}
static int countOccurrences(String text, String target) {
int count = 0;
for (int i = text.indexOf(target); i >= 0; i = text.indexOf(target, i + target.length())) {
count++;
}
return count;
}
static String padLeft(String s, int width, char pad) {
return s.length() >= width ? s : String.valueOf(pad).repeat(width - s.length()) + s;
}
static String abbreviate(String s, int max) {
return s.length() <= max ? s : s.substring(0, max - 3) + "...";
}
static boolean isAsciiDigits(String s) {
return !s.isEmpty() && s.chars().allMatch(c -> c >= '0' && c <= '9');
}
static String toCamelCase(String snake) {
StringBuilder sb = new StringBuilder();
boolean upper = false;
for (char c : snake.toCharArray()) {
if (c == '_') {
upper = true;
} else {
sb.append(upper ? Character.toUpperCase(c) : c);
upper = false;
}
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println("capitalize: " + capitalize("java") + ", " + capitalize("\u00E9cole")
+ ", " + capitalize("") + ", " + capitalize(null));
System.out.println("reverse: " + new StringBuilder("Hello, World").reverse());
System.out.println("palindrome: " + isPalindrome("A man, a plan, a canal: Panama")
+ ", " + isPalindrome("\u00C9t\u00E9") + ", " + isPalindrome("hello"));
System.out.println("count: " + countOccurrences("one fish two fish red fish", "fish")
+ ", overlapping \"aa\" in \"aaaa\": " + countOccurrences("aaaa", "aa"));
System.out.println("padLeft: "
+ padLeft("42", 6, '0') + " " + padLeft("1234567", 6, '0'));
System.out.println("abbreviate: " + abbreviate("A considerably longer title", 15));
System.out.println("digits: "
+ isAsciiDigits("2026") + " " + isAsciiDigits("20a6") + " "
+ isAsciiDigits("") + " " + isAsciiDigits("\u0664\u0662"));
System.out.println("camelCase: " + toCamelCase("order_line_item"));
System.out.println("swapcase: " + "Hello".chars()
.map(c -> Character.isUpperCase(c)
? Character.toLowerCase(c) : Character.toUpperCase(c))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append));
}
}
Output:
capitalize: Java, École, , null
reverse: dlroW ,olleH
palindrome: true, true, false
count: 3, overlapping "aa" in "aaaa": 2
padLeft: 000042 1234567
abbreviate: A considerab...
digits: true false false false
camelCase: orderLineItem
swapcase: hELLO
works on the first code point and usescapitalize , so it is correct forCharacter.toTitleCase and for characters outside the BMP, and it returns empty and null input unchanged.école- Reversing with
keeps surrogate pairs together. The palindrome check removes everything that is not a letter or digit in any script (StringBuilder.reverse ,\p{L} ), so\p{N} is detected; an ASCII-only class such asÉté would drop the accented letters.[^A-Za-z] moves past each match, socountOccurrences occurs 2 times inaa . TheaaaaindexOf page shows the overlapping variant. leaves strings that are already long enough alone;padLeft does the same for numbers.String.format("%06d", n) keeps the total length at the limit, here 15, including the three dots.abbreviate rejects the empty string and Arabic-Indic digits, whichisAsciiDigits would accept. Choose deliberately which one your validation needs.Character.isDigit- Converting
toorder_line_item and swapping case are simple loops over characters.orderLineItem
Handling null
Every StringNullPointerExceptionnullStringUtils
import java.util.Objects;
import java.util.Optional;
public class NullSafety {
static boolean isNullOrBlank(String s) {
return s == null || s.isBlank();
}
static String defaultIfBlank(String s, String fallback) {
return isNullOrBlank(s) ? fallback : s;
}
public static void main(String[] args) {
String missing = null;
String blank = " ";
String name = " Ada ";
System.out.println("isNullOrBlank: " + isNullOrBlank(missing) + " " + isNullOrBlank(blank)
+ " " + isNullOrBlank(name));
System.out.println("defaultIfBlank: [" + defaultIfBlank(blank, "anonymous") + "]");
System.out.println("requireNonNullElse: "
+ Objects.requireNonNullElse(missing, "n/a")); // Java 9
System.out.println("Objects.toString(null, \"-\"): " + Objects.toString(missing, "-"));
System.out.println("String.valueOf((Object) null): " + String.valueOf((Object) null));
System.out.println("Objects.equals: " + Objects.equals(missing, null) + " "
+ Objects.equals(name.strip(), "Ada"));
// Optional chains for "trim it if present, else a default"
String cleaned = Optional.ofNullable(missing).map(String::strip).filter(s -> !s.isEmpty())
.orElse("unknown");
System.out.println("Optional chain: " + cleaned);
// Concatenation turns null into "null", which is rarely wanted
System.out.println("\"Hello, \" + missing = " + "Hello, " + missing);
try {
System.out.println(missing.length());
} catch (NullPointerException e) {
System.out.println("missing.length(): " + e.getMessage());
}
}
}
Output:
isNullOrBlank: true true false
defaultIfBlank: [anonymous]
requireNonNullElse: n/a
Objects.toString(null, "-"): -
String.valueOf((Object) null): null
Objects.equals: true true
Optional chain: unknown
"Hello, " + missing = Hello, null
missing.length(): Cannot invoke "String.length()" because "<local1>" is null
- A one-line
helper covers the most common check.isNullOrBlank builds on it to supply a fallback.defaultIfBlank (Java 9) andObjects.requireNonNullElse (Java 7) return a default for null.Objects.toString(o, default) returns the textString.valueOf((Object) null) .null compares safely when either side may be null.Objects.equals- An
chain expresses "strip it if present, otherwise use a default" without nestedOptional statements.if - Concatenation turns null into the four letters
, which ends up in messages and files unnoticed.null - Since Java 14 (JEP 358), the exception message says what was null. The variable appears as
here because the class was compiled without<local1> ; with debug information it shows the name-g .missing
The JDK compared with StringUtils
Many projects use Apache Commons Lang only for StringUtilsStringUtils
| StringUtils | JDK equivalent | Difference |
|---|---|---|
isBlank(s)isEmpty(s) | s == null || s.isBlank()s.isEmpty() | The JDK methods throw on null |
strip(s)trim(s) | s.strip()s.trim() | Same rules for non-null input |
repeat(s, n) | s.repeat(n) | None for non-null input |
join(...) | String.joinCollectors.joining | StringUtils.join |
defaultIfBlank(s, d) | A one-line helper | No JDK method |
capitalize(s) | The recipe above | No JDK method |
leftPad(s, n, c) | String.formatrepeat | No JDK method for strings |
abbreviate(s, n) | The recipe above | No JDK method |
countMatches(s, t) | An indexOf | No JDK method |
isNumeric(s) | chars().allMatch(Character::isDigit) | isNumeric |
If a project already depends on Commons Lang, its null-tolerant methods are a reasonable choice. For new code with no such dependency, the JDK methods and a handful of small helpers are usually enough.
Are the new methods faster?
The new methods were added for clarity, but some are also faster than the idioms they replace. The program compares three pairs, keeping the quickest of three runs.
import java.util.function.Supplier;
public class UtilSpeed {
static Object sink;
public static void main(String[] args) {
String text = "row data value\n".repeat(200000);
String padded = " " + "x".repeat(40) + " ";
System.out.println("splitting 200,000 lines:");
time("text.lines().count()", () -> text.lines().count());
time("text.split(\"\\\\R\").length", () -> text.split("\\R").length);
time("text.split(\"\\n\").length", () -> text.split("\n").length);
System.out.println("1,000,000 blank checks on a 46-char string:");
time("isBlank()", () -> {
int n = 0;
for (int i = 0; i < 1000000; i++) {
n += padded.isBlank() ? 1 : 0;
}
return n;
});
time("trim().isEmpty()", () -> {
int n = 0;
for (int i = 0; i < 1000000; i++) {
n += padded.trim().isEmpty() ? 1 : 0;
}
return n;
});
System.out.println("building a 1,000,000-char separator:");
time("\"-\".repeat(n)", () -> "-".repeat(1000000).length());
time("StringBuilder loop", () -> {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
sb.append('-');
}
return sb.length();
});
}
// Best of 3 runs
static void time(String name, Supplier<Object> work) {
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
sink = work.get();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-28s %7.2f ms (%s)%n", name, best / 1e6, sink);
}
}
Output (rough timings; 2-CPU Linux machine, JDK 21):
splitting 200,000 lines:
text.lines().count() 4.23 ms (200000)
text.split("\\R").length 20.88 ms (200000)
text.split("\n").length 19.85 ms (200000)
1,000,000 blank checks on a 46-char string:
isBlank() 7.62 ms (0)
trim().isEmpty() 32.19 ms (0)
building a 1,000,000-char separator:
"-".repeat(n) 2.26 ms (1000000)
StringBuilder loop 2.97 ms (1000000)
streams the lines lazily without building an array, and counting them was three to five times faster thanlines() .split("\\R") skips the regex engine but was no faster, because it still creates all 200,000 strings and an array; it also ignoressplit("\n") .\r\n stops at the first non-whitespace character and allocates nothing, whileisBlank() creates a new 40-character string each time beforetrim() is checked. It was four to fifteen times faster across runs, and the gap grows with the length of the text.isEmpty() computes the final size and fills the array in one step. A simple append loop was in the same range in these runs, so the gain there is clarity rather than speed.repeat
Which method to use
| Task | Use |
|---|---|
| Repeat text or build a separator line | s.repeat(n) |
| Check for no real content | s == null || s.isBlank() |
| Trim user input | s.strip() |
| Process text line by line | s.lines() |
| Indent or dedent a block | indent(n)stripIndent() |
| Fill a template | "...".formatted(args) |
| Escapes in text read at run time | translateEscapes() |
| Capitalize, abbreviate, pad, count | The small recipes above, or StringUtils |
| Values that may be null | Objects.toStringObjects.equalsOptional |
For searching, replacing and comparing, see