Working with Modern String Features

1. Using Text Blocks

FeatureDetail
SyntaxTriple-quoted """
TypeSame String instance — interned if all-literal
Use casesJSON, 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"
RuleDetail
Common indentCalculated from minimum leading whitespace including closing """
Trailing newlineClosing """ on new line includes \n
No newlinePlace """ right after last char

3. Using Text Block Escape Sequences (\, \s, \n)

EscapeMeaning
\ at line endLine continuation (suppress newline)
\sSignificant trailing space
\n \t \"Standard escapes still work
"""Use \""" for literal triple quotes

4. Using Text Block with formatted()

Example: formatted

String query = """
        SELECT * FROM users
        WHERE id = %d AND active = %b
        """.formatted(userId, true);
MethodBehavior
.formatted(args)Same as String.format(s, args)

5. Using String.indent() Method

CallEffect
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

6. Using String.transform() Method

Example: transform

Integer parsed = "42".transform(Integer::parseInt);
String upper = "hello".transform(String::toUpperCase);
AspectDetail
Signature<R> R transform(Function<String,R> f)
Use caseFunctional pipelines on a single string

7. Using String.isBlank() Method

MethodReturns
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);
AspectDetail
ReturnsStream<String>
Line terminators\n, \r, \r\n all recognized
No trailing newlinesLines are stripped of terminator

9. Using String.repeat() Method

CallResult
"ab".repeat(3)"ababab"
"x".repeat(0)Empty string
Negative countIllegalArgumentException

10. Understanding String Templates

StatusDetail
Java 21Preview (STR."...")
Java 23Withdrawn for redesign
Current alternative 2026Use "...%s...".formatted(x) or String.format
Warning: String templates are not yet stable as of Java 21 LTS — use formatted() for now.