Working with Modern String Features
1. Using Text Blocks
| Feature | Detail |
| Syntax | Triple-quoted """ |
| Type | Same String instance — interned if all-literal |
| Use cases | JSON, SQL, HTML, multi-line messages |
2. Understanding Text Block Indentation
Example: Indentation handling
String s = """
line1
line2
line3
""";
// Common leading whitespace stripped → "line1\n line2\nline3\n"
| Rule | Detail |
| Common indent | Calculated from minimum leading whitespace including closing """ |
| Trailing newline | Closing """ on new line includes \n |
| No newline | Place """ right after last char |
3. Using Text Block Escape Sequences (\, \s, \n)
| Escape | Meaning |
\ at line end | Line continuation (suppress newline) |
\s | Significant trailing space |
\n \t \" | Standard escapes still work |
""" | Use \""" for literal triple quotes |
4. Using Text Block with formatted()
String query = """
SELECT * FROM users
WHERE id = %d AND active = %b
""".formatted(userId, true);
| Method | Behavior |
.formatted(args) | Same as String.format(s, args) |
5. Using String.indent() Method
| Call | Effect |
s.indent(n) | Adds n spaces to each line; ensures trailing \n |
s.indent(-n) | Removes up to n leading whitespace from each line |
s.indent(0) | Normalizes line endings |
Integer parsed = "42".transform(Integer::parseInt);
String upper = "hello".transform(String::toUpperCase);
| Aspect | Detail |
| Signature | <R> R transform(Function<String,R> f) |
| Use case | Functional pipelines on a single string |
7. Using String.isBlank() Method
| Method | Returns |
isEmpty() | true if length 0 |
isBlank() | true if empty or only whitespace (Unicode-aware) |
8. Using String.lines() Method
Example: Stream of lines
"a\nb\r\nc".lines()
.filter(l -> !l.isBlank())
.forEach(System.out::println);
| Aspect | Detail |
| Returns | Stream<String> |
| Line terminators | \n, \r, \r\n all recognized |
| No trailing newlines | Lines are stripped of terminator |
9. Using String.repeat() Method
| Call | Result |
"ab".repeat(3) | "ababab" |
"x".repeat(0) | Empty string |
| Negative count | IllegalArgumentException |
10. Understanding String Templates
| Status | Detail |
| Java 21 | Preview (STR."...") |
| Java 23 | Withdrawn for redesign |
| Current alternative 2026 | Use "...%s...".formatted(x) or String.format |
Warning: String templates are not yet stable as of Java 21 LTS — use formatted() for now.