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 String class changed little, and projects filled the gaps with their own helpers or with Apache Commons Lang's StringUtils. Since Java 11, almost every release has added a few methods. They are all instance methods on an immutable string, so each returns a new string (or the same one when nothing changes) and none accepts null as the receiver.

String methods added since Java 8
MethodSinceReplaces
String.join, chars()Java 8Join loops; index loops over chars
repeat(n)Java 11Loops that append the same text
isBlank()Java 11trim().isEmpty()
strip(), stripLeading(), stripTrailing()Java 11trim(), which only knows ASCII
lines()Java 11split("\\R")
indent(n), transform(f)Java 12Indentation helpers; temporary variables
formatted(args), stripIndent(), translateEscapes()Java 15String.format; text block helpers
indexOf(ch, begin, end), splitWithDelimitersJava 21substring before searching; lookaround splits
StringBuilder.repeatJava 21Padding 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.

Java
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:

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
  • repeat(0) returns the empty string and a negative count throws IllegalArgumentException with "count is negative: -1".
  • isBlank() is true for the empty string, for whitespace-only text and for the em space U+2003, because it uses Character.isWhitespace. It is false for " x ". More about which characters count is on the whitespace page.
  • strip removes whitespace from both ends, and the leading and trailing variants from one end only.
  • lines() recognizes \n, \r\n and a lone \r, so the mixed text gave 4 lines. A final terminator does not create an empty last line, the empty string has 0 lines, and "\n\n" has 2 empty lines.
  • Character.toString(int), also new in Java 11, turns a code point into a string; the G clef needs 2 chars.

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.

Java
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:

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!!!
  • indent(4) adds four spaces to each line, keeping relative indentation. indent(-2) removes up to two leading spaces per line, never more than a line has, so c was unchanged. indent always ends the result with \n and normalizes \r\n to \n, even with indent(0).
  • transform 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.
  • formatted is String.format with the template as the receiver, convenient after a text block; see the formatting page.
  • stripIndent removes the indentation common to all lines, as the compiler does for text blocks. translateEscapes interprets escape sequences such as \t, \n and the octal \101 (the letter A) in text read at run time, but rejects \u, because Unicode escapes are handled by the compiler before strings exist.
  • Java 21's indexOf('a', 2, 4) searches only indexes 2 and 3 and found the a at 3. splitWithDelimiters keeps the separators as elements; see the split page.
  • StringBuilder.repeat appends a string or a character a number of times and returns the builder, so it chains.

Recipes for tasks with no built-in method

Some everyday operations still have no method on String. Each recipe below is a few lines long, and the test values include the inputs where the naive versions break: an accented first letter, an empty string, null, overlapping matches and non-ASCII digits.

Java
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:

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
  • capitalize works on the first code point and uses Character.toTitleCase, so it is correct for école and for characters outside the BMP, and it returns empty and null input unchanged.
  • Reversing with StringBuilder.reverse keeps surrogate pairs together. The palindrome check removes everything that is not a letter or digit in any script (\p{L}, \p{N}), so Été is detected; an ASCII-only class such as [^A-Za-z] would drop the accented letters.
  • countOccurrences moves past each match, so aa occurs 2 times in aaaa. The indexOf page shows the overlapping variant.
  • padLeft leaves strings that are already long enough alone; String.format("%06d", n) does the same for numbers.
  • abbreviate keeps the total length at the limit, here 15, including the three dots.
  • isAsciiDigits rejects the empty string and Arabic-Indic digits, which Character.isDigit would accept. Choose deliberately which one your validation needs.
  • Converting order_line_item to orderLineItem and swapping case are simple loops over characters.

Handling null

Every String method throws NullPointerException when called on null, which is the main reason libraries like StringUtils are popular. The JDK has enough pieces to handle null explicitly, and the program uses a null, a blank and a padded value to show them.

Java
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:

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 isNullOrBlank helper covers the most common check. defaultIfBlank builds on it to supply a fallback.
  • Objects.requireNonNullElse (Java 9) and Objects.toString(o, default) (Java 7) return a default for null. String.valueOf((Object) null) returns the text null.
  • Objects.equals compares safely when either side may be null.
  • An Optional chain expresses "strip it if present, otherwise use a default" without nested if statements.
  • Concatenation turns null into the four letters null, which ends up in messages and files unnoticed.
  • Since Java 14 (JEP 358), the exception message says what was null. The variable appears as <local1> here because the class was compiled without -g; with debug information it shows the name missing.

The JDK compared with StringUtils

Many projects use Apache Commons Lang only for StringUtils. Modern Java covers most of it; the main differences are that StringUtils methods are static and accept null, and that it has a few helpers the JDK lacks.

StringUtils methods and their JDK equivalents
StringUtilsJDK equivalentDifference
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.join, Collectors.joiningStringUtils.join accepts any objects
defaultIfBlank(s, d)A one-line helperNo JDK method
capitalize(s)The recipe aboveNo JDK method
leftPad(s, n, c)String.format or repeatNo JDK method for strings
abbreviate(s, n)The recipe aboveNo JDK method
countMatches(s, t)An indexOf loopNo JDK method
isNumeric(s)chars().allMatch(Character::isDigit)isNumeric also accepts other scripts' digits

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.

Java
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):

Output
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)
  • lines() streams the lines lazily without building an array, and counting them was three to five times faster than split("\\R"). split("\n") skips the regex engine but was no faster, because it still creates all 200,000 strings and an array; it also ignores \r\n.
  • isBlank() stops at the first non-whitespace character and allocates nothing, while trim() creates a new 40-character string each time before isEmpty() is checked. It was four to fifteen times faster across runs, and the gap grows with the length of the text.
  • repeat 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.

Which method to use

Choosing a utility method
TaskUse
Repeat text or build a separator lines.repeat(n)
Check for no real contents == null || s.isBlank()
Trim user inputs.strip()
Process text line by lines.lines()
Indent or dedent a blockindent(n), stripIndent()
Fill a template"...".formatted(args)
Escapes in text read at run timetranslateEscapes()
Capitalize, abbreviate, pad, countThe small recipes above, or StringUtils
Values that may be nullObjects.toString, Objects.equals, Optional

For searching, replacing and comparing, see indexOf, replace and string comparison.