3.4 Essential Modern String Methods
← Back to Chapter 3: Strings in Java
Java 11 through Java 21 introduced several high-utility methods to java.lang.String that eliminate the need for third-party libraries like Apache Commons Lang.
1. Modern String Inspection (Java 11+)
String empty = "";
String whitespace = " \t\n ";
// isBlank() checks if length is 0 OR contains only whitespace codepoints
System.out.println(empty.isEmpty()); // true
System.out.println(whitespace.isEmpty()); // false
System.out.println(whitespace.isBlank()); // true (Modern check)
2. Advanced Whitespace Stripping: strip() vs trim()
| Method | Whitespace Definition | Handling Unicode Spaces |
|---|---|---|
trim() | Character code <= \u0020 (ASCII space only) | Fails on Unicode whitespace (e.g. non-breaking space \u00A0) |
strip() | Full Unicode Character.isWhitespace(codepoint) | Accurately strips all international Unicode whitespace |
Java also provides directional stripping:
String text = " Java 21 ";
System.out.println("'" + text.stripLeading() + "'"); // 'Java 21 '
System.out.println("'" + text.stripTrailing() + "'"); // ' Java 21'
3. Transformations & Multi-line Operations
// repeat(n): Repeat a string N times
String divider = "=".repeat(30);
// lines(): Stream lines separated by \n or \r\n
String multiLine = "First\nSecond\r\nThird";
List<String> lines = multiLine.lines()
.map(String::toUpperCase)
.toList();
// join(): Static string joiner
String csv = String.join(", ", "Apple", "Banana", "Cherry"); // "Apple, Banana, Cherry"
// formatted(): Modern alternative to String.format() (Java 15)
String log = "User %s logged in with ID: %d".formatted("sarvy", 42);