The String.indent(int n)
method in Java is a useful tool for formatting multi-line strings by adjusting the amount of leading space (indentation) on each line. Introduced in Java 12, it performs the following for the specified n
indentation:
- Positive
n
: Addsn
spaces to the beginning of each line in the string. - Negative
n
: Removes up ton
leading spaces from each line. - Zero
n
: Leaves the string unchanged (but trims blank lines at the start/end).
This is particularly useful for formatting text in structured views, like logs, JSON, XML, or pretty-printed output.
Example: Using String.indent
to Format Output
Here is how you can use the String.indent()
method:
package org.kodejava.lang;
public class StringIndentExample {
public static void main(String[] args) {
// Original multi-line string (no indentation)
String text = "Line 1\nLine 2\nLine 3";
// Adding an indent of 4 spaces
String indented = text.indent(4);
System.out.println("Indented by 4 spaces:\n" + indented);
// Removing 2 leading spaces (negative indent)
String negativeIndent = indented.indent(-2);
System.out.println("Indented with -2 (removing spaces):\n" + negativeIndent);
// Applying indent to empty lines
String withEmptyLines = "Line 1\n\nLine 3";
String indentedWithEmptyLines = withEmptyLines.indent(4);
System.out.println("Handling empty lines:\n" + indentedWithEmptyLines);
}
}
Explanation of Code:
- Adding Indentation: The first call to
.indent(4)
adds 4 spaces to each line. - Removing Indentation:
.indent(-2)
deducts 2 spaces from the start of each line (if spaces exist). - Empty Lines: When dealing with blank lines,
indent
maintains the level of indentation for such lines, adding or removing spaces as needed.
Output:
Indented by 4 spaces:
Line 1
Line 2
Line 3
Indented with -2 (removing spaces):
Line 1
Line 2
Line 3
Handling empty lines:
Line 1
Line 3
Notes:
- Empty lines and their indentation are preserved.
- Lines with no leading spaces are unaffected by negative indentation.
- Leading and trailing full blank lines are removed.
When to Use:
- To format multiline strings cleanly.
- To produce human-readable or formatted output in tools or commands (e.g., logging, text processing).