Introduction
Java 11 shipped in September 2018 with a handful of new instance methods on the String class, delivered through JEP 324 and the broader Java 11 API additions. The headline methods are isBlank, lines, repeat, strip, stripLeading, stripTrailing, and indent. Together they replace the verbose, error-prone utility code that every Java developer had been writing for years: "s.trim().length() == 0" for blank checks, manual for-loops with substring for line splitting, StringBuilder in a loop for repetition, and Pattern.compile for trimming Unicode whitespace.
For a Java learner, java 11 string methods is the moment the String class caught up with Python's str methods, JavaScript's String.prototype, and Kotlin's String extensions. This post shows each method, the difference from the older trim, and the way they pair for text-processing pipelines.
What is the Java 11 String Methods?
The new String methods belong to the family of String utility operations, alongside the legacy Java 1.0 trim, Java 7 isEmpty, and Java 8 chars and codePoints. The new methods are instance methods on java.lang.String, so they are called on any String value. None of them mutate the original String; like every String operation since Java 1.0, they return a new String because String is immutable.
The crucial improvement over the legacy trim is Unicode awareness. trim removes characters whose code point is less than or equal to U+0020, which covers ASCII space, tab, newline, carriage return, and a few control characters but not the Unicode whitespace characters like U+00A0 (no-break space), U+2007 (figure space), or U+3000 (ideographic space). strip uses Character.isWhitespace, which recognises the full Unicode whitespace set. For ASCII-only input the two methods produce the same output; for international text they differ.
How the Java 11 String Methods Work - Step by Step
Step 1: Use isBlank for blank checks. isBlank returns true if the String is empty or contains only whitespace. The legacy "s.trim().isEmpty()" pattern is replaced by "s.isBlank()". Unlike isEmpty, which only returns true for the empty String, isBlank returns true for " " as well.
Step 2: Use lines for line splitting. lines returns a Stream<String> of the lines of the String, splitting on line terminators \n, \r, and \r\n. Unlike split("\\R"), which produces a trailing empty string for input that ends with a newline, lines does not. The Stream is lazy, so the split happens as the stream is consumed.
Step 3: Use repeat for repetition. "x".repeat(3) returns "xxx". The argument is the number of copies; repeat(0) returns the empty string, repeat(1) returns the same string, and repeat with a negative argument throws IllegalArgumentException. The implementation is efficient: it does not use string concatenation in a loop, it builds a char array of the right size and fills it.
Step 4: Use strip, stripLeading, and stripTrailing for Unicode-aware trimming. strip removes both leading and trailing Unicode whitespace. stripLeading removes only leading whitespace, stripTrailing only trailing. The difference from trim is the Unicode awareness described above.
Step 5: Use indent for indentation. indent(n) returns a new String with n spaces prepended to every line. A positive n adds spaces; a negative n removes up to |n| leading whitespace from each line. indent(0) normalises line endings to \n and appends a trailing newline if one is missing.
Java Program for the Java 11 String Methods
import java.util.stream.Collectors;
public class StringMethodsDemo {
public static void main(String[] args) {
// (1) isBlank - true for empty and whitespace-only strings
String empty = "";
String spaces = " ";
String tabs = "\t\t\t";
String text = "hello";
System.out.println("(1) "".isBlank() = " + empty.isBlank());
System.out.println(" " ".isBlank() = " + spaces.isBlank());
System.out.println(" \"\\t\\t\\t\".isBlank() = " + tabs.isBlank());
System.out.println(" "hello".isBlank() = " + text.isBlank());
// (2) lines - returns Stream<String> of lines
String poem = "roses are red\nviolets are blue\n";
var lineList = poem.lines().collect(Collectors.toList());
System.out.println("(2) line count = " + lineList.size());
for (int i = 0; i < lineList.size(); i++) {
System.out.println(" line " + i + " = " + lineList.get(i));
}
// (3) repeat - "abc".repeat(3) = "abcabcabc"
String ab = "ab".repeat(3);
System.out.println("(3) "ab".repeat(3) = " + ab);
String zero = "x".repeat(0);
System.out.println(" "x".repeat(0) = "" ? " + zero.isEmpty());
try {
"x".repeat(-1);
} catch (IllegalArgumentException ex) {
System.out.println(" repeat(-1) threw: " + ex.getClass().getSimpleName());
}
// (4) strip - Unicode-aware trim of both ends
String padded = " hello ";
String noBreakSpace = "\u00A0hi\u00A0"; // no-break space
System.out.println("(4) strip(" hello ") = '" + padded.strip() + "'");
System.out.println(" stripLeading = '" + padded.stripLeading() + "'");
System.out.println(" stripTrailing = '" + padded.stripTrailing() + "'");
System.out.println(" trim vs strip on no-break space:");
System.out.println(" trim = '" + noBreakSpace.trim() + "' length=" + noBreakSpace.trim().length());
System.out.println(" strip = '" + noBreakSpace.strip() + "' length=" + noBreakSpace.strip().length());
// (5) indent - add or remove leading whitespace per line
String src = "line1\nline2\nline3";
String indented = src.indent(2);
String dedented = " a\n b\n c".indent(-2);
System.out.println("(5) indent(+2):");
System.out.println(indented);
System.out.println(" indent(-2):");
System.out.println(dedented);
// (6) Realistic pipeline: clean up a CSV-like input
String raw = " alice, 30 \n bob , 25 \n carol, 40 ";
String cleaned = raw.lines()
.map(String::strip)
.map(line -> line.replaceAll("\\s*,\\s*", ","))
.collect(Collectors.joining("\n"));
System.out.println("(6) cleaned CSV:");
System.out.println(cleaned);
// (7) Repeat for separator construction
String divider = "-".repeat(40);
System.out.println("(7) divider = " + divider);
// (8) Lines + repeat for boxed output
String[] names = {"alice", "bob", "carol"};
StringBuilder boxed = new StringBuilder();
boxed.append("+").append("-".repeat(10)).append("+\n");
for (String n : names) {
boxed.append("| ").append(n);
int pad = 9 - n.length();
if (pad > 0) boxed.append(" ".repeat(pad));
boxed.append("|\n");
}
boxed.append("+").append("-".repeat(10)).append("+");
System.out.println("(8) boxed output:");
System.out.println(boxed);
// (9) indent(0) normalises line endings
String mixed = "windows\r\nmac\runix\n";
String normalised = mixed.indent(0);
System.out.println("(9) indent(0) replaces \r and \r\n with \n:");
System.out.println(" before CRs = " + countChar(mixed, '\r'));
System.out.println(" after CRs = " + countChar(normalised, '\r'));
// (10) strip + isBlank to filter blank lines
String block = "header\n\n \nbody line 1\n\nbody line 2";
var nonBlank = block.lines()
.filter(line -> !line.isBlank())
.collect(Collectors.toList());
System.out.println("(10) non-blank lines = " + nonBlank);
}
static int countChar(String s, char ch) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ch) count++;
}
return count;
}
}
Code Explanation - Line by Line
Section (1) demonstrates isBlank on four inputs: the empty string, a string of spaces, a string of tabs, and the string "hello". The first three return true; the last returns false. The legacy equivalent "s.trim().isEmpty()" would produce the same results, but isBlank is a single call and is more readable.
Section (2) demonstrates lines on a two-line poem that ends with a newline. The lines() stream splits on \n, \r, and \r\n. Because the input ends with a newline, split would produce a trailing empty string, but lines does not: the count is 2, not 3. The for loop prints each line with its index. Note that the last line "violets are blue" is returned without the trailing newline.
Section (3) demonstrates repeat. "ab".repeat(3) returns "ababab" by concatenating three copies of the source string. The output also shows repeat(0) returns the empty string, which is the identity element for concatenation, and repeat(-1) throws IllegalArgumentException with the message "count is negative: -1". The implementation is efficient: it does not build the result by string concatenation in a loop, which would be O(n squared) due to the immutability of String; instead it allocates a char array of length source.length times count, fills it with repeated copies of the source, and wraps it in a new String.
Section (4) demonstrates strip, stripLeading, and stripTrailing. For " hello ", strip returns "hello", stripLeading returns "hello " (trailing spaces preserved), and stripTrailing returns " hello" (leading spaces preserved). The crucial demonstration is the no-break space U+00A0: trim does not remove it because its code point is 0xA0 which is greater than 0x20, but strip does remove it because Character.isWhitespace returns true for U+00A0. The output shows trim length 4 (the no-break spaces and "hi") while strip length 2 (just "hi").
Section (5) demonstrates indent. indent(2) prepends two spaces to every line. indent(-2) removes up to two leading spaces from every line; if a line has fewer than two leading spaces, all of them are removed. indent(0) does not change the indentation but normalises line endings to \n and appends a trailing newline if one is missing.
Section (6) is a realistic pipeline that uses lines, strip, replaceAll, and Collectors.joining to clean up a CSV-like input. Each line is stripped of leading and trailing whitespace, then the whitespace around the comma is collapsed to just a comma. The result is a clean "alice,30\nbob,25\ncarol,40" string.
Section (7) uses repeat to construct a 40-character divider. The legacy approach was a for-loop that appended "-" to a StringBuilder 40 times; the new approach is a single call. Section (8) combines repeat with a for-loop to produce a boxed table. The pad calculation uses 9 minus the name length, and " ".repeat(pad) fills the gap. The boxed output shows the table borders aligned.
Section (9) demonstrates the indent(0) line-ending normalisation. The mixed string "windows\r\nmac\runix\n" has both \r\n (Windows) and \r (old Mac) and \n (Unix) line endings. indent(0) replaces every \r\n and every \r with \n, so the resulting string has only \n line endings. The countChar helper counts the \r characters before and after; the output shows before = 2 and after = 0.
Section (10) is the practical filter pattern. The block string has blank lines, including one with whitespace. The pipeline uses lines() to split, filter with !line.isBlank() to drop blanks and whitespace-only lines, and collect(Collectors.toList()) to materialise the result. The output shows only the two non-blank lines: "header" and "body line 1" and "body line 2".
Sample Input and Output
(1) "".isBlank() = true
" ".isBlank() = true
" ".isBlank() = true
"hello".isBlank() = false
(2) line count = 2
line 0 = roses are red
line 1 = violets are blue
(3) "ab".repeat(3) = ababab
"x".repeat(0) = "" ? true
repeat(-1) threw: IllegalArgumentException
(4) strip(" hello ") = 'hello'
stripLeading = 'hello '
stripTrailing = ' hello'
trim vs strip on no-break space:
trim = ' hi ' length=4
strip = 'hi' length=2
(5) indent(+2):
line1
line2
line3
indent(-2):
a
b
c
(6) cleaned CSV:
alice,30
bob,25
carol,40
(7) divider = ----------------------------------------
(8) boxed output:
+----------+
| alice |
| bob |
| carol |
+----------+
(9) indent(0) replaces
and
with
:
before CRs = 2
after CRs = 0
(10) non-blank lines = [header, body line 1, body line 2]
The output confirms every contract point. isBlank returns true for empty, whitespace, and tabs. lines splits correctly without a trailing empty string. repeat(3) produces "ababab"; repeat(0) returns empty; repeat(-1) throws. strip removes both leading and trailing spaces; stripLeading and stripTrailing remove only one end. trim fails to remove the no-break space (U+00A0) while strip does remove it. indent(+2) and indent(-2) work as described. The CSV cleanup produces the expected clean output. The divider is 40 dashes. The boxed table aligns the names. The line-ending normalisation removes the carriage returns. The blank-line filter drops the two blank lines.
Common Mistakes to Avoid
The first mistake is using trim when you mean strip. trim is ASCII-only and leaves Unicode whitespace like U+00A0, U+2007, and U+3000 in place. For international text, always prefer strip. The second mistake is using split("\\R") to split lines and being surprised by the trailing empty string when the input ends with a newline. Use lines() instead, which does not produce a trailing empty string.
The third mistake is using a StringBuilder in a loop to repeat a string. "ab".repeat(3) is one call and the JDK implementation uses an efficient char array; a manual loop is both slower and harder to read. The fourth mistake is calling strip() and expecting the original String to change. String is immutable; strip returns a new String, so you must capture the result.
The fifth mistake is using indent on a single-line string and expecting the indent to apply only at the start. indent applies to every line in the string, so a single-line string gets a leading-space prefix and a trailing newline; multi-line strings get the prefix on every line. The sixth mistake is using indent(0) and expecting no change; indent(0) normalises line endings and appends a trailing newline if one is missing, which is observable behaviour.
The seventh mistake is assuming repeat handles negative counts by returning an empty string. It throws IllegalArgumentException; you must guard negative inputs yourself. The eighth mistake is assuming isBlank() is the same as isEmpty() on a trimmed string; isBlank is more permissive because it returns true for whitespace-only strings, not just empty ones.
Real-World Applications
The Java 11 String methods are used throughout the Java standard library. java.util.Formatter uses isBlank in the format-spec parsing; java.io.StringReader uses lines in the readAllLines helper; java.util.stream.Collectors.joining uses repeat in the indent-augmented variants of the joining collector. The Apache Commons Lang StringUtils class has been updated to delegate to the JDK strip and isBlank when the input is a single String, and the Spring Framework StringUtils uses isBlank in its hasText helper.
In the wider ecosystem, JUnit 5's @CsvSource uses lines to split the CSV input; Mockito uses repeat to construct matcher error messages; Apache POI uses strip in the cell-string normalisation pipeline; the Google JSON parser uses stripLeading and stripTrailing to clean up whitespace between tokens. The Kotlin standard library has equivalent extension functions that delegate to the JDK methods when the underlying String is a java.lang.String. Studying java 11 string methods is therefore the prerequisite for writing clean text-processing pipelines in modern Java and for understanding the whitespace-handling rules that Unicode-aware libraries depend on.
Conclusion
We showed isBlank, lines, repeat, strip, stripLeading, stripTrailing, and indent with their Unicode-aware semantics and the contrast with the legacy trim and isEmpty. The Java 11 String methods replaced the verbose utility code that every Java developer had been writing for years, and they are the standard way to handle text in modern Java source. The natural next topics to study are the Java 13 text blocks (triple-quoted strings) that build on the same line-handling machinery, and the Java 12 String transform method that lets you pipe String operations through a Function.
Comments
Comments
Post a Comment